Search code examples
c#object-reference

Reference form objects in C# to avoid repeating code blocks


I've tried searching for this, but my problem might be I don;t know the correct terms to describe the problem.

I have a C# form, with a number of textbox objects.

At some I process the contents of each textbox in sequence as follows:

tbxStressCmd1.BackColor = Color.Salmon;
processCmd(tbxStressCmd1.Text);
System.Threading.Thread.Sleep( tbxStressWait1.text );
tbxStressCmd1.BackColor = Color.White;

tbxStressCmd2.BackColor = Color.Salmon;
processCmd(tbxStressCmd2.Text);
System.Threading.Thread.Sleep( tbxStressWait2.text );
tbxStressCmd1.BackColor = Color.White;
.
tbxStressCmd9.BackColor = Color.Salmon;
processCmd(tbxStressCmd9.Text);
System.Threading.Thread.Sleep( tbxStressWait9.text );
tbxStressCmd9.BackColor = Color.White;

I'd like to avoid the repitition and have something like:

// Pseudo Code
runCmd ( object tbxCmd, object tbxWait )
{
   tbxCmd.BackColor = Color.Salmon;
   processCmd(tbxCmd.Text);
   System.Threading.Thread.Sleep( tbxWait.text );
   tbxCmd.BackColor = Color.White;
}

Then:

runCmd( tbxStressCmd1, tbxStressWait1 );
.
.
runCmd( tbxStressCmd9, tbxStressWait9 );

What is the correct way to reference textbox objects such that they can be passed to functions and used as in the above pseudo code?


Solution

  • You are passing a variable of type TextBox as object to the method, You are not passing the actual type. Which is here, I suppose, TextBox. If you don't pass the actual type, you can't manipulate the properties of that type. You will just see & deal with the type as if it was of the type you use to pass the argument which is Object here Since TextBox derive from the base class Object. You can take a look at Object class members. You can't see a Text property there :). You can do this:

    public void DoTheThing(TextBox txCmd, TextBox txWait){
        txCmd.BackColor = Color.Salmon;
        ProcessCmd(txCmd.Text);
        System.Threading.Thread.Sleep(txWait.Text)
        txCmd.BackColor = Color.White;
    }
    

    I'd like to finish with some notes:

    1. First You can't pass a string value to System.Threading.Thread.Sleep. You should do something called casting or type conversion. You can search for these terms. To do that, C# provide you with a helper class Convert. You can use the helper method ToInt32 to convert the value in the TextBox to Int32 value type.

    2. If you want to implement a "waiting" or "delay" effect, in a UI application or in a UI-Thread context. I suggest you use Task.Delay instead, and await the returned delay task, and mark your method with async modifier. This is called Asynchronous Programming