views:

75

answers:

2

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

 mylabel.text = "Text for label"
or this.mylabel.tex = "TExt for my label"

Which of these is right way, Is there simple explanation when to use this keyword when using controls in WinForms, Such as datagrid, texlables and others

+5  A: 

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.

Kirk Woll
+7  A: 

Hi adopilot,

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).

sidewinderguy
Yes. Using some naming convention over using `this` to disambiguate is the way to go.
John
Explicitly discouraged by the .NET style guide. Thinking of calling it "ungarian". Maybe "resharpian".
Hans Passant