Possible Duplicate:
What is the purpose of 'this' keyword in C#.
Hello,
I have a question about something. I have had a look around, but can't seem to figure it out.
Why do some programmers use this
in-front of something? Like:
this.button1 = String.Empty;
In MSDN, I don't ever recall seeing this.
being used unless this.
was referring to the Form itself, like this:
this.WindowState = FormWindowState.Minimized;
Is this how we're really supposed to reference things? Or, are there added benefits to doing it this way? So far, I have not experienced any noticeable benefits, not have I noticed any changes.
Thank you :-)
the keyword this
is often used as a way to be explicit in where a variable is coming from. For example, a large function might have many variables, and using this may be used to tell what are true properties for a class being set, and what are function variables.
Also, consider the example below, where it's necessary to use the keyword to distinguish between a class variable and function parameter.
object one;
object two;
public MyClass(object one, object two)
{
this.one = one;
this.two = two;
}
Actually, you use this
to reference the container object. Using this
is usefull sometimes in solving some conflection cases as the following:
public class Person
{
private String name;
public Person(String name)
{
this.name = name;
}
}
However you can avoid using this by changing the name of the private field/variable:
public class Person
{
private String _name;
public Person(String name)
{
_name = name;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With