Proper way to use data throughout a class?

I know global variables aren't a thing in c#, as that goes against the rules.
So I have a couple of functions and subroutines (pardon my vocabulary if it isn't canon). I use a simple array to transfer data back and forth. Is this the proper way to do this? As in most efficient, readable, and expandable?
class Program
static void Main()
bool[] MotorPosition = new bool[4];
MotorPosition[0] = true;
MotorPosition[1] = false;
MotorPosition[2] = true;
MotorPosition[3] = false;
while (true)
MotorPosition = UpdateMotorPosition(MotorPosition);
DisplayMotorPosition(MotorPosition);
System.Threading.Thread.Sleep(64);
static bool[] UpdateMotorPosition(bool[] MotorPosition)
bool[] NewMotorPosition = new bool[4];
for (int x = 0; x < 4; x = x + 1)
NewMotorPosition[x] = !MotorPosition[x];
return NewMotorPosition;
static void DisplayMotorPosition(bool[] MotorPosition)
string CombinedDisplay = null;
for (int x = 0; x < 4; x = x + 1)
CombinedDisplay = CombinedDisplay + MotorPosition[x].ToString();
Console.WriteLine(CombinedDisplay);
Mediocre Access 2010 | (Baby) Beginner C Sharp | OK at Active Directory (2012) | Fragmented understanding of DNS/DHCP | Laughable experience with Group Policy | Expert question asker on MSDN Forums

Absolutely amazing! I learn something new every day. I wonder when programming will cease to amaze me.
using your example jdweng, I was able to add a counter to your code and move the motor position to the test class; as well as add another motor by instancing the class again!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
class Program
static int Main(string[] args)
Test test = new Test();
test.Initialize(); //Assigns initial value to MotorPosition
Test test2 = new Test();
test2.Initialize(); //Assigns initial value to MotorPosition
while (true)
if (test.MotorUpdateCount == 40) Console.ReadLine(); //pauses at 40 to make it easy to see output upto that point
if (test.MotorUpdateCount > 1000) return -1; //ends program
test.MotorPosition = test.UpdateMotorPosition(test.MotorPosition); //updates motor 1 position
test.DisplayMotorPosition(test.MotorPosition); //displays motor 1 position
if (test.MotorUpdateCount > 20) //at count 20, engages motor 2
test2.MotorPosition = test2.UpdateMotorPosition(test2.MotorPosition); //updates motor 2 position
test2.DisplayMotorPosition(test2.MotorPosition); //displays motor 2 position
System.Threading.Thread.Sleep(128); //slows the loop down to reasonable speed
public class Test
public int MotorUpdateCount = 0;
public bool[] MotorPosition = new bool[4];
public void Initialize()
MotorPosition[0] = true;
MotorPosition[1] = false;
MotorPosition[2] = true;
MotorPosition[3] = false;
public bool[] UpdateMotorPosition(bool[] MotorPosition)
bool[] NewMotorPosition = new bool[4];
for (int x = 0; x < 4; x = x + 1)
NewMotorPosition[x] = !MotorPosition[x];
MotorUpdateCount = MotorUpdateCount + 1;
return NewMotorPosition;
public void DisplayMotorPosition(bool[] MotorPosition)
string CombinedDisplay = null;
for (int x = 0; x < 4; x = x + 1)
CombinedDisplay = CombinedDisplay + MotorPosition[x].ToString();
Console.WriteLine(CombinedDisplay);
Console.WriteLine(MotorUpdateCount.ToString());
Mediocre Access 2010 | (Baby) Beginner C Sharp | OK at Active Directory (2012) | Fragmented understanding of DNS/DHCP | Laughable experience with Group Policy | Expert question asker on MSDN Forums

Similar Messages

  • What is the proper way to use the write method?

    What is the proper way to use the OutputStreams write method? I know the flush() method is automatically called after the write but i cant seem to get any output
    to a file. The char array contains characters and upon completion of the for loop the contents of the array is printed out, so there is actually data in the array. But write dosnt seem to do squat no matter what i seem to do. Any suggestions?
    import java.io.*;
    public class X{
    public static void main(String[] args){
    try{      
    FileReader fis = new FileReader("C:\\Java\\Test.txt"); //read chars
    FileWriter fw = new FileWriter("C:\\Java\\Test1.txt"); //read chars
    File f = new File("C:\\Java\\Test.txt");
    char[] charsRead = new char[(int)f.length()];
    while(true){
    int i = fis.read(charsRead);
    if(i == -1) break;
    // fw.write(charsRead); this wont work
    // but there is infact chars in the char Array?
    for(int i = 0; i < charsRead.length -1 ; ++i){
    System.out.print(charRead);
    }catch(Exception e){System.err.println(e);}

    Sorry to have to tell you this guys but all of the above are broken.
    First of all... you should all take a good look at what the read() method actually does.
    http://java.sun.com/j2se/1.3/docs/api/java/io/InputStream.html#read(byte[], int, int)
    Pay special attension to this paragraph:
    Reads up to len[i] bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len[i] bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer.
    In other words... when you use read() and you request say 1024 bytes, you are not guaranteed to get that many bytes. You may get less. You may even get none at all.
    Supposing you want to read length bytes from a stream into a byte array, here is how you do it.int bytesRead = 0;
    int readLast = 0;
    byte[] array = new byte[length];
    while(readLast != -1 && bytesRead < length){
      readLast = inputStream.read(array, bytesRead, length - bytesRead);
      if(readLast != -1){
        bytesRead += readLast;
    }And then the matter of write()...
    http://java.sun.com/j2se/1.3/docs/api/java/io/OutputStream.html#write(byte[])
    write(byte[] b) will always attempt to write b.length bytes, no matter how many bytes you actually filled it with. All you C/C++ converts... forget all about null terminated arrays. That doesn't exist here. Even if you only read 2 bytes into a 1024 byte array, write() will output 1024 bytes if you pass that array to it.
    You need to keep track of how many bytes you actually filled the array with and if that number is less than the size of the array you'll need pass this as an argument.
    I'll make another post about this... once and for all.
    /Michael

  • Is it a proper way to use queue for consumer/producer model?

    Hi all,
      I am following the example of consumer/producer model to use the queue to synchronize the following process: The producer is a loop to produce N numbers, I will put every generated number into an array and after every 5 numbers generated, I put the array into the queue and pass it to the consumer. I have to wait the consumer use up the data and it will then remove the element from queue so the producer will get a chance to produce another 5 numbers. Since I set the maximum size of the queue to be ONE, I expect the producer and consumer take turns to produce / consume all five numbers and pass the chance to the other. Here is my code
    when the case box is false, the code will be
    For the first 5 numbers, the produce will generate every thing right and put that into the array, and it will pass the array to the quere so the consumer will get a chance to loop over the array. I except the procude's loop will continue only when the queue is available (i.e. all elements are removed), but it seems that once the consumer start the loop the produce 's loop will continue (so the indicator x+1 and x+2 will show numbers changed). But it is not what I want, I know there must be something wrong but I can't tell what is it.
    Solved!
    Go to Solution.

    dragondriver wrote:
    As you said in 1, the sequency structure enforcing the execution order, that's why I put it there, in this example, to put the issue simple, I replace the complete code with number increase, in the real case, the first +1 and +2 must be executed in that order.
    Mikeporter mentioned:
    1. Get rid of all the sequence structures. None of them are doing anything but enforcing an execution order that would be the same without them.
    So even if you remove the sequence structure, there will be a fixed & defined execution order and that is because LabVIEW follows DATA FLOW MODEL.
    Data Flow Model (specifically in context of LabVIEW): A block diagram node executes when it receives all required inputs. When a node executes, it produces output data and passes the data to the next node in the dataflow path. The movement of data through the nodes determines the execution order of the VIs and functions on the block diagram (Click here for reference).
    Now in your code, just removing the sequence structure will not make sure that the execution order will gonna remain same but you need to do few very small modifications (like pass the error wire through For loop, before it goes to 'Dequeue Element' node).
    Coming to the main topic: is it a proper way to use queue for consumer/producer model?
    The model you're using (and calling it as consumer/producer model) is way too deviated from the original consumer/producer model model.
    dragondriver wrote:
    For the second one, yes, it is my fault to remove that while. I actually start from the example of Producer/Consumer design pattern template, but I didn't pay attention to the while loop in the consumer part.
    While loops (both Producer & Consumer) are the essential part of this architecture and can't be removed. You may want to start your code again using standard template.
    I am not allergic to Kudos, in fact I love Kudos.
     Make your LabVIEW experience more CONVENIENT.

  • What's the proper way to use reusingView in a custom UIPickerView

    Does anyone have an example of the proper way to use the resuingView parameter when implementing pickerView:viewForRow:forComponent:reusingView: in a UIPickerViewDelegate?
    The documentation states that reusingView is "A view object that was previously used for this row, but is now hidden and cached by the picker view."
    and: "If the previously used view (the view parameter) is adequate, return that. If you return a different view, the previously used view is released. The picker view centers the returned view in the rectangle for row."
    I need to create UILabel views so I can right justify things, and I have that working by always returning my copy of the view, but it seems like things could be made more efficient by returning the view passed to me if it's "adequate". So, how do I tell if the view is adequate?
    I've tried something like this:
    // check to see if the view we're given is a UILabel and return that view
    if ([view isMemberOfClass:[UILabel class]])
    v = (UILabel *)view;
    return v;
    else
    ... return a UILabel instance for this row ...
    But the view I'm being passed is never a UILabel instance. That or I'm not using isMemberOfClass correctly.
    Thoughts anyone?

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    iPregnancyAppDelegate *iPregAppDelegate = [[UIApplication sharedApplication] delegate];
    UILabel *pickerLabel = (UILabel *)view;
    // Reuse the label if possible, otherwise create and configure a new one
    if ((pickerLabel == nil) || ([pickerLabel class] != [UILabel class])) { //newlabel
    CGRect frame = CGRectMake(0.0, 0.0, 270, 32.0);
    pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    pickerLabel.textAlignment = UITextAlignmentLeft;
    pickerLabel.backgroundColor = [UIColor clearColor];
    pickerLabel.text = @"Put YOUR text here!";
    return pickerLabel;
    Message was edited by: gpmoore

  • What is the proper way to use Siri dictation with punctuation, on iPad with Retina Display?

    What is the proper way to use Siri dictation with punctuation, on iPad with Retina Display?
    Thank you!

    From the iPad User Manual:
    Also:
    no space on ... no space off—to run a series of words together
    smiley—to insert :-)
    frowny—to insert :-(
    winky—to insert ;-)

  • Best or proper way to Use a Mophie Helium with iPhone 5s

    What would be the recommended way to use a Mophie Helium with a iPhone 5s?  Use the phone battery as primary and recharge from the Mophie as needed or use the Mophie battery first and then the iPhone? The later is what Mophie shows in their ops manual but I would like to hear Apples opinion on the issue.

    Based on this http://www.mophie.com/shop/iphone-5/juice-pack-helium-iphone-5, it would not appear that using the Morphie first is what is recomended. since it is essentailly a charging mechaism, frankly, that wouldn't make any sense.
    BTW: this is a user-to-user forum, so Apple will not offer an opinion here.

  • Best way to use library movieclips with classes?

    Hi,
    I've created a carousel class which takes one parameter, an array of menu item names, these will then be displayed on the carousel. I've then created  two movieclips for the left and right controls, added them to the library and given them classes of their own.
    Within the carousel class I instantiate instances of the two control classes which then enables me to add event listeners for rollover and rollout.
    What I'd like to know is, is this the best way to do this short of creating the controls using pure actionscript?
    I'd like to not have to add the class properties for the left and right controls and have a situation where I could just give them the right name and they would work or maybe pass them in as parameters and use them that way.
    Any tips for how you would go about doing this would be much appreciated.
    Thanks,
    eb_dev

    Have you tried something that isn't working?  If I understand what your intentions are, I would think that the approach would be to create Class ID's for the clips and import the classes into the carousel class.

  • Proper way to use JMenuBar?

    I want to use a JMenuBar to produce some "redundant" functionality into my program. Say, for instance, the user wants to print something. I can have a print button on screen an a print option in the file menu. I can have both objects call a static printRecords() menu in one of my other classes. This part isn't a problem.
    The problem I think I'm going to run into is JMenu items that try to reproduce the functionality of actions in classes that it doesn't have access to. Say, for instance, I have a JPanel full of JTextFields and it also has a button that says "Clear Fields." Currently, my design has the implementation for the button in the JPanel class. This works except that the JMenu does not have access to this method.
    What's the best approach to reducing the amount of code that I have to reuse without passing information all over the place?

    Assuming you still care about this issue (or that others do), I know I'm coming back long time after...
    The only class that I extend is the JPanel class because it makes it easier
    to create and manage the complex layout that I need.
    Are you suggesting there is a better way (...) without extending JPanel?Yes.
    Write business logic in non-graphic classes, write interaction logic into dedicated classes (depending on swing API but not extending any JComponent), and write the building and wiring of graphical components to the intercation classes in a dedicated composer class (you're right I made up this term, I don't know if a generally accepted one exists).
    I looked up the term "composer class" but couldn't find anything.
    Can you go into more detail about this term?Something along the line of:// Simple class, one text field, one clear button
    public class MyGUIComposer
      public void JFrame composeScreen()
      JFrame theFrame = new JFrame();
      JPanel mainPanel = new JPanel();
      mainPanel.setLayout(...)
      JPanel subPanel1 = new JPanel();
      final JTestField myTextField = new JTextField(...);
      Action buttonLogic = new ClearAction(myTextField);
      JButton clearButton = new JButton(buttonLogic);
    }With ClearAction.actionperformed() methods being as simple as the TextField.cleartext();
    If the configuration of the screen is more complex (e.g. lots of text fields, other widgets,...), you can use a Mediator class (this one is a known and documented design pattern). See below.
    Also, I figured I could use the same Action for the different components
    but (...)
    how would a "Clear" Action have a handle to the fields it needs to clear?It should have a handle to a Mediator object: this latter has already references to all widgets. And the clear action does not even bother clearing all buttons but just ask the Mediator to do so.
    The Mediator can itself be the composer, in this case the creation of the action becomes:
           Action buttonLogic = new ClearAction(this); // this being the mediator instanceand ClearAction.actionPerformed() becomes as simple as
    public void actionPerformed() { theMediator.clearAllFields();}And of course you write the mediator class with the method clearAllFields() which iterates through all relevant fields and clears them.
    At first it looks much more convoluted, but the Mediator really comes handy when you add features to your UI : more widgets, more interactions, more conditions (e.g. clear button clears all fields and adds a message in the status bar, and greys out the submit button only if the "Enable empty names" option is false.
    I find it better than having a JPanel subclass having to pass around the value of all options.

  • Proper way to use multiple pop-up dialogs

    I've got an application that uses a series of pop-ups to process user information.
    A general flow of information is
    User clicks a button
    ->dialog launches asking for confirmation to start process
    Dialog returns and system processes request (in a returnListener)
    ->System launches new dialog, using AdfFacesContext.launchDialog, asking user to confirm changes to be made
    Dialog returns and systems processes changes.
    What I've noticed is that if I interact with the components in the second dialog 'too much' then the second return listener is not being called.
    So, my question is, am I using dialogs properly? Should I try to use actions and navigation links instead of opening and closing dialogs?

    Sounds reasonable.
    In that vein, is there a way to create 're-usable' dialogs? Ideally I don't want to have to write tons of little dialog that do nothing more interesting than asking "Are you sure?" with the actions set differently.
    At first glance, I'm almost tempted to pack a method binding into the process scope and have the dialog check if it exists, and if it does, execute that. But that seems somewhat, inelegant.
    Any thoughts?

  • Proper way to use a compressor

    I have a bass line that is sitting well in the mix when I put the channel fader to -12 db.
    But there are ocassional peaks that take the signal into Red.
    So before I apply compression to this track should I first put the channel fader down until the signal stops going in the red? Or do I leave the channel fader as it is and then go ahead and mess with the compressor?

    In this case, the answer is clear. Adjust your levels first.
    If you try to fix this using only compression, it will totally flatten anything above the threshold point. That will cause a substantial loss of dynamic range. Far better to maintain that dynamic range since that will make the line more vibrant and musical.
    So, take the level down a touch and apply a compressor. Keep listening and adjusting. By the way, you might like to try using Channel EQ in the path before a compressor. That way, you can take the level down of certain frequencies and still keep the ones that you need in your mix.
    Just to be quite clear, though, the fader operates after all the inserts have done their stuff. When you move the fader down, you're not taking down the signal and then applying compression. What you're doing is taking the hot spots out of the signal with the compressor and then using the fader to mix the treated signal.
    If you really want to take the signal down before applying compressor, use channel EQ (which will, of course change the flavour of your sound) or use the Gain insert (found under Insert > Utility) before the Compressor insert.
    Pete

  • Proper way to use cpCmndExit

    Hello all:
    I am attempting to create a "fast Exit" button. On Success, the button is calling an Advanced Action called QuikExit. QuiKExit is a Standard Action and is structured as
    Assign cpCmndExit with 1
    From what little I can find, this should elicit an exit to the movie but when I publish and try it, NADA!
    Any Ideas as to what I am missing?

    Hi there
    The PDF may not recognize that Captivate is the only thing inside of it. As a result, something like a command to close the window may be ignored from something like Captivate because there could be other content inside the PDF. So in my own guess here, it's more of a PDF security thing.
    I'll also speculate that only a member of the Captivate development team can really answer or explain that in better technical detail.
    Cheers... Rick
    Helpful and Handy Links
    Captivate Wish Form/Bug Reporting Form
    Adobe Certified Captivate Training
    SorcerStone Blog
    Captivate eBooks

  • Can you place text from a word document using data merge?

    I'm working with a charity that is giving away scholarships/grants. I need to create a ducument that pulls in various application data plus their submitted essay (docx format). I would like to do this via data merge but cannot find any reference if it is possible.
    Please help, I really need to automate as much as possible since this is a side project.
    Kevin

    Data merge only collects info from CSV format - which I expect you would export from Excel. (I think it'll take tab-delimited as well, but that's it.)
    MS Word files can be placed, but Data Merge is not the tool to automate placing of Word-file content. If there is no formatting of their essays, I suspect you could use VBA to cause entire essays to occupy a single cell in Excel. But that would be the only way to use Data Merge to automate import of essays into InDesign.
    Maybe if you tell us more we can give you some more automation suggestions. (I spend a lot of time automating translation workflows, but I still place Word files. All day long, in fact.)
    (edited for spelling)

  • Best Approach for using Data Pump

    Hi,
    I configured a new database which I set up with schemas that I imported in from another production database. Now, before this database becomes the new production database, I need to re-import the schemas so that the data is up-to-date.
    Is there a way to use Data Pump so that I don't have to drop all the schemas first? Can I just export the schemas and somehow just overwrite what's in there already?
    Thanks,
    Nora

    Hi, you can use the NETWORK_LINK parameter for import data from other remote database.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/dp_import.htm#i1007380
    Regards.

  • How to use commit work in class cl_bls

    Hi,
    When i have used commit work after email sent,
    it goes into dump.
    Here is the code segment:
      try.
        -------- create persistent send request ------------------------
          send_request = cl_bcs=>create_persistent( ).
        -------- create and set document -------------------------------
          pdf_content = cl_document_bcs=>xstring_to_solix( pdf_tab ).
          document = cl_document_bcs=>create_document(
                i_type    = 'PDF'
                i_hex     = pdf_content
                i_length  = bytecount
                i_subject = sub ).  "#EC NOTEXT
        add document object to send request
          send_request->set_document( document ).
        --------- add recipient (e-mail address) -----------------------
        create recipient object
          recipient = cl_cam_address_bcs=>create_internet_address( recip-recip ).
        add recipient object to send request
          send_request->add_recipient( recipient ).
        ---------- send document ---------------------------------------
          sent_to_all = send_request->send( i_with_error_screen = 'X' ).
         commit work.
          if sent_to_all is initial.
            message i500(sbcoms) with recip.
          else.
            message s022(so).
          endif.
      ------------ exception handling ----------------------------------
      replace this rudimentary exception handling with your own one !!!
        catch cx_bcs into bcs_exception.
          message i865(so) with bcs_exception->error_type.
      endtry.
    What could be the reason?
    Is there any way to use commit work in class while sending email as in SO_NEW_DOCUMENT_ATT_SEND_API1 fm?
    Thanks.

    Hi,
    I have used
    submit program.....
    but in update task i have used it.
    "Z_SD_ORDER_UPDATE".    program is a print driver program.
    However error says:
    There is probably an error in the program
    "Z_SD_ORDER_UPDATE".  
    This program is triggered in the update task. There, the
    following ABAP/4 statements are not allowed:
    -  CALL SCREEN
    -  CALL DIALOG
    -  CALL TRANSACTION
    -  SUBMIT
    I used submit as:
      WAIT UP TO 2 SECONDS.
      SUBMIT rsconn01 WITH mode = 'INT'
                      WITH output = ' '
                    AND RETURN.
    Instead of submit i want to use commit work but i also get a dump after commit work too.
    How can i use commit work in above code?
    Thanks.

  • Copying a new .class file for WLS to use, proper way?

    Hello. I'm doing some servlet development and I would like to know what is
    the proper way to deploy any .class files and servlets (also .class files)?
    If I just copy them into the proper directory, am I supposed to have to
    restart the server? Is that normal, or should WLS just pick up the new one?
    It does that with JSPs, can it do that with servlets and supporting classes?
    Thanks.

    I found out that I was copying the wrong file to the right place (.java
    instead of the .class :<). So once I fixed that small little :> problem, I
    was off and running. Thank you for your help! :>
    "Slava Imeshev" <[email protected]> wrote in message
    news:[email protected]..
    Hi Peter,
    Normally weblogic will redeploy automatically application, either web
    or ejb, without restarting the server, when it's copied to applications
    directory on the server. Applications should be properly packaged.Servlets
    and supported files should be in war file, ejb-s in ejb-jar files.
    I'm not sure if it would work right for plain unpacked class files.
    Regards,
    Slava Imeshev
    "PeterH" <!REMOVEBeforeSending! > wrote in message
    news:[email protected]..
    Hello. I'm doing some servlet development and I would like to know whatis
    the proper way to deploy any .class files and servlets (also .classfiles)?
    If I just copy them into the proper directory, am I supposed to have to
    restart the server? Is that normal, or should WLS just pick up the newone?
    It does that with JSPs, can it do that with servlets and supportingclasses?
    Thanks.

Maybe you are looking for

  • Getting unique values from an arraylist

    Hi I have an arraylist that contains stringbuffer objects. The arraylist has duplicate values of the objects. I have to create another arraylist with only the unique values from the first arraylist. I tried it many ways and using many functions, but

  • How can I make the webpage display the same on different sized screens?

    I have made a webpage, but it appears differently in different resolutions. I am in 1920x1080 and it appears fine on my screen, but anything smaller than that, the text is zoomed in more and it is not central. website can be found here: http://www.fi

  • Will Mountain lion will support the creation of Galleries

    Does anyone know if Mountain lion will support the creation of Galleries like the ones produced on mobile me - I need to do this for business purposes - and does anyone have a good sugestion for an alternative - photoshop galleries lack a little flai

  • WL 7.0 sp4 session replication problem

              These are the configuration:           * BEA WebLogic Server 7.0 SP4           * Domain : mydomain           * Machine:           machine1 (Windows 2003)           machine2 (Windows 2000)           * Admin Server :           myserver (on "m

  • Oracle db installation

    Hi When do you want to install a fresh oracle software and database into unix operating system. In general which one method is be used? 1-)create database ..... 2-) Oracle universal installer