Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some use `this.`? [duplicate]

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

like image 754
Lucifer Avatar asked Nov 27 '22 21:11

Lucifer


2 Answers

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;
}
like image 90
William Melani Avatar answered Dec 05 '22 04:12

William Melani


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;
    }
}
like image 43
Akram Shahda Avatar answered Dec 05 '22 03:12

Akram Shahda