4

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

9
  • 2
    @Barry: I don't think it's an exact duplicate. The other question explains what this means, not why it is used like @Lucifer desribes in the auto-generated Forms code. Commented Jun 1, 2011 at 7:11
  • 1
    @Anders Abel What is the difference of asking for a purpuse and asking for why people use it?. This qustion should just be closed Commented Jun 1, 2011 at 7:13
  • 2
    @Lucifer: I would say you were working with legacy code done using VS2003. There one have to wire up even handlers in code. there I have seen this this. a lot. now its irrelevant I guess. btw whats this.button1 = String.Empty; :) Commented Jun 1, 2011 at 7:16
  • 1
    @AndersAbel: I disagree, the question I have linked to not only explains the various ways of using this but also states where you don't have to use this. i.e. in the example posted by the OP. If you don't agree then don't cast a close vote :) Commented Jun 1, 2011 at 7:16
  • 1
    @Barry; I don't believe this is an exact duplicate, as @Anders A mentioned, for the same reason. :)
    – Lucifer
    Commented Jun 1, 2011 at 7:29

12 Answers 12

10

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;
}
8

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;
    }
}
7
  • Yes! By Container object, you mean the Form? Panel? etc etc? That's what I was kind of thinking. But then again, like the others have noted, it works fine without it. :-S
    – Lucifer
    Commented Jun 1, 2011 at 7:12
  • 1
    No, not the form, panel .. I mean the object that contains the logic that is currently executing .. Commented Jun 1, 2011 at 7:15
  • 1
    @Matías Fidemraizer: Thanx. I've updated my answer to include your note. However, it is a subjective matter as you already know. Commented Jun 1, 2011 at 7:30
  • 1
    @Matias: Even without the edit, the answer didn't say you had to use it, just that it could be used to disambiguate. No downvote necessary. Using other names is only another alternative. Commented Jun 1, 2011 at 7:32
  • 4
    +1 For the correction. All naming guidelines are absolutely subjective and arbitrary, and this is why all of them are "guidelines", aren't they? :D I believe that C# has few cases where "this" keyword is really useful. For example, if you need to give current instance as argument of some method. But I won't vote for using it for disambiguation. Commented Jun 1, 2011 at 7:32
6

This means this object: if you're in a form that's a form, if you are in a simple class, that's your class. We're not supposed to use it (it's implicit), but sometimes you need it to make code very clear or it is necessary when:

class MyClass
{
    private int tot = 0;
    public MyClass(int tot)
    {
        this.tot = tot;
    }
}
2
  • This is the entire reason. this is never necessary except to regain access to a field that has been shadowed by another symbol with the same name. Unfortunately, exactly this style is common practice in setters and constructors, and many people over-generalize it because they see it done so often, without understanding why. Commented Jun 1, 2011 at 7:23
  • @Kilian Foth: I agree, but because of compiler strips it away it's not so bad. For readability is not good. Anyway you're right, people often use this without knowing why :)
    – Marco
    Commented Jun 1, 2011 at 7:27
6

Do take a look at http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.71).aspx. Mostly we use it to ensure that we are referring to members of a class that might be hidden. The MSDN example is:

public Employee(string name, string alias) 
{
   this.name = name;
   this.alias = alias;
}
0
5

Using this keyword in your code will differentiate which ones area the properties and methods of the class you are currently in scope. Also this means that we are using the instance methods and properties, not the static methods and properties.

This also means we have to instantiate it first.

Therefore, it will improve readability and the meanings of your code, especially in a large team of software developers where the code will be shared to others.

4

Something like this.button1 is necessary when there's another button1 in a more local scope than your object.

4

The this. notation is systematically used by the windows forms generator, this is maybe where you saw it.

this. is used for disambiguation when a member variable name is the same as a method parameter, for example.

Other than that, it's a matter of taste, but I believe most programmers do not use it because it's long to type (but a bit more readable, I'd say).

2
  • it's not a bit more readable, it's truly a lot more readable. if you are working in a large team of software developers, this use of ''this'' is extremely useful for other members of your team, since your code will be used and shared to other members. Commented Jun 1, 2011 at 7:28
  • I find this to be much less readable. It's distracting clutter. I prefer code to be concise and economical, just as I prefer prose to be concise and economical. So it's truly a matter of opinion. If you are working in a large team of software developers, conform to the team's standard, since your code will be used by and shared with the rest of the team.
    – phoog
    Commented Jun 1, 2011 at 8:58
4

Remember that using "this." is sometimes mandatory. As an example, when assigning field values with the same name as constructor arguments, e.g.

public class MyClass{
    private string name;

    public MyClass(string name) {
        this.name = name; // <== This is mandatory
    }
}
3

for compiler it is the same. Form has controls as fields, and adding the this keyword simply remids the reader that we are using Form fields

3

It's unnecessary (the code will work fine without it), however it does make it clearer as to where the method or field belongs. If you use StyleCop on its most picky settings, Microsoft recommend this style.

Edit: Actually, most of the time it is unnecessary, but as several other answers have mentioned, it is sometimes necessary for conflict resolution.

3
SomeNameSpace.SomeClass.SomeMethod() 
SomeNameSpace.SomeClass.OtherMethod()

when you're within SomeMethod(), say you want to call OtherMethod(). Using this prevents you from having to write SomeNameSpace.SomeClass.OtherMethod() every time that you want to use it.

Since you're within SomeClass already, this will reference SomeClass when you're working inside of SomeMethod(). So all you have to do to reference OtherMethod() is go: this.OtherMethod()

It's a nice shortcut that will also make your programs easier to maintain in the future, should you need to change SomeNameSpace or SomeClass to other names.. this will still work how you intended it to.

namespace Foo {
  public class Bar {
    public void Method() {
      // Do Other Stuff
    }
    public void OtherMethod() {
      // Do Some Stuff
      this.Method(); // Do Other Stuff
      // Instead of Foo.Bar.Method()
    }
  }
}
6
  • Ohhhh.. That's pretty cool! Thank you!
    – Lucifer
    Commented Jun 1, 2011 at 7:19
  • 3
    -1 because inside the class, neither SomeClass. is required, nor is this.. You can simply call OtherMethod(). Unless I totally misunderstand what you're talking about, in which case you should still improve your description with a code sample :) Commented Jun 1, 2011 at 7:22
  • 1
    @Merlyn, I updated the answer with a code example. hopefully that has more clarity.
    – tester
    Commented Jun 1, 2011 at 8:13
  • 1
    @tester: Hmm, that's what I thought you meant. Try throwing it in your compiler, and changing this.Method(); to Method();. this. will compile, but is unnecessary, and that's what the original question is about - why use this.Method(); when you can use Method(); Commented Jun 1, 2011 at 8:15
  • 3
    In fact, Foo.Bar.Method(); will not compile, because Foo.Bar.Method() is the syntax for calling a static method, while this Method() is an instance method. You may only call it as this.Method(); or Method();
    – phoog
    Commented Jun 1, 2011 at 8:52
1

It is not mandatory but I believe the main reason for following this practice is to improve readability. As an example it makes it very easy for the reader to distinguish between local variables and method parameters.

public class User
{
    string firstname;
    string lastname;

    public User(string firstname, string lastname)
    {
        this.firstname = firstname;
        this.lastname = lastname;
    }
}
2
  • 5
    That's not exactly true. Some would argue that having this all over the place actually makes code less readable. Using this will disambiguate what exactly you are referencing, so it's about explicitness not readability. Commented Jun 1, 2011 at 7:13
  • 1
    @marnix-van-valen I agree. It's something that should be used when it will improve readability but not always Commented Jun 1, 2011 at 7:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.