Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use THIS keyword when working with controls on form in C#

I am still far away from mastering C#, but the child in me is pushing me to continue improving my programming day by day.
When I make a WinForms application I want to change and use lot of controls pragmatically.
What I do not understand is when I need to use the this.control keyword and when I should use just control.
Sample:
If I want to change the text of my label I can write

mylabel.text = "Text for label"

or

this.mylabel.tex = "Text for label"

Which of these is the right way? Is there a simple explanation when to use the this keyword when using controls in WinForms (such as datagrid, text, tables, etc.)?

like image 297
adopilot Avatar asked Aug 06 '10 23:08

adopilot


People also ask

What will you use if you want to add controls to your form?

Adding controls to the form is an easy task, what you need to do is drag a control from the toolbox and drop it onto the form or draw it on the form. You can drag the control around the form and you can also resize it easily.

What is the use of control class in Windows form creation?

NET Framework. The Control class implements very basic functionality required by classes that display information to the user. It handles user input through the keyboard and pointing devices.

Which of the following is used to run a form in main method in C#?

In the main function, you could add this: Form1 c = new Form1(); c. ShowDialog(); Both methods will show your form as a dialog.

Which property of control sets the text that will be displayed on control?

In this article For example, a Button control usually displays a caption indicating what action will be performed if the button is clicked. For all controls, you can set or return the text by using the Text property. You can change the font by using the Font property.


2 Answers

In this case, both of those lines are "correct". However, the use of "this" is not needed here.

One reason to use "this" is if you need to resolve an ambiguity. "this" gives you unambiguous access to the members of a class. Here's an example:

class Test
{
   public void SetNumber(int number)
   {
      this.number = number;
   }

   private int number;
}

In this example, you must use "this" to refer to the class member "number" and assign to it the value in the passed in argument with the same name ("number").

Of course, it would be better to have a naming convention that prevents this. I tend to put an underscore in front of private member data (ie. _number).

like image 196
sidewinderguy Avatar answered Nov 14 '22 23:11

sidewinderguy


It's only strictly necessary when you are diambiguating between a field/property and a local variable. Others prefer to use it in other places, but that's a style decision.

like image 45
Kirk Woll Avatar answered Nov 14 '22 23:11

Kirk Woll