4

I sometimes need to go online and find a tutorial for something. I am often finding that some people put code like this:

this.button1.Text = "Random Text";

Then I find code that is just like this:

button1.Text = "Random Text";

Is it better to use the this.whatever or does it not matter?

Dozer789
  • 1,980
  • 2
  • 23
  • 43

11 Answers11

10

It depends. Here's an example class:

class A
{
    private int count;
    public A(int count)
    {
        this.count = count;
    }
}

In this case, the "this." is mandatory because it disambiguates the reference on the left of the assignment. Without it, it is not clear to you reading the code whether "count" would refer to the parameter or the field. (It is clear to the compiler, which has rules to follow.) But in most cases, it is purely a matter of preference.

David M
  • 71,481
  • 13
  • 158
  • 186
7

Write all your code to emphasize salient points to the reader. If you feel that it is important for the reader to clearly understand that an identifier refers to an instance member then use this. If you feel that its an unimportant and distracting implementation detail, don't. Use good judgment to make your code readable.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
3

It does not matter, it is a matter of style. I tend to omit this, since it is just extra code to mentally parse.

The only case it matters is when there is a naming conflict between local and instance variables, in which case this can be used to disambiguate between a field and a local variable.

Here is an example of the type of situation where it does matter:

public class Foo
{
    private string x;

    public Foo(string x)
    {
        // x = x;      Assigns local parameter x to x, not what we want
        this.x = x; // Assigns instance variable x to local parameter x: this disambiguates between the two.
    }
}
driis
  • 161,458
  • 45
  • 265
  • 341
3

this is just to make it clear, in some cases we have to use this:

  1. Differentiate between parameter and local member:

    //local member
    object item;
    private void SomeMethod(object item){
        this.item = item;//must use this
    }
    
  2. Pass the current class instance into another method:

    public class SomeClass {
      private void SomeMethod(SomeClass obj){
         //....
      }
      private void AnotherMethod(){
        SomeMethod(this);//pass the current instance into SomeMethod
        //.....
      }
    }
    
  3. Use in extension methods:

    public static class SomeClassExtension {
        public static void SomeClassMethod(this SomeClass obj){
            //use obj as a reference to the object calling this method...
        }
    }
    
  4. Call a constructor from another constructor (with different signature):

    public Form1(string s) : this() {//Call the Form1() before executing other code in Form1(string s)
       //......
    }
    
  5. Use for declaring indexers:

    public class SomeClass {
       //declare an index returning a string
       public string this[int index] {
          get {return ...}
          set { ... }
       }
    }
    
  6. Use auto-properties in struct:

    public struct SomeStruct {
       public object AutoProp1 {get;set;}
       public object AutoProp2 {get;set;}
       public SomeStruct() : this() //must use this
       {
          AutoProp1 = someObject;
          AutoProp2 = someObject;
       }
    }
    
  7. Cast the current instance to the based classes/types:

    public class ClassB : ClassC {
        //...
    }
    public class ClassA : ClassB {
        public ClassA(){
           ((ClassC)this).MemberOfClassC ... ;//There might be some member in ClassC
           //which is overridden in ClassA or ClassB, casting to ClassC can help we invoke the original member instead of the overridden one.
        }
    }
    

There might be some other uses of this, however I'll update later if I think out.

King King
  • 61,710
  • 16
  • 105
  • 130
2

an example of using this can be to access class variable when you already have a similar variable in the scope. Otherwise it is mostly of choice.

Example

public class Test
{
    public string firstName { get; set; }       

    public void temp(string firstName)
    {
        firstName = this.firstName;
    }
}
Ehsan
  • 31,833
  • 6
  • 56
  • 65
2

In regards to fields the only case where this is explicitly needed is when there is a naming conflict:

public class Foo
{
    private string bar;

    public Foo(string bar)
    {
        this.bar = bar;
    }
}

So some will prepend an underscore:

public class Foo
{
    private string _bar;

    public Foo(string bar)
    {
        _bar = bar;
    }
}
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
2

Usually it will not matter. This reason why you might use this. is to explicit say that you want to reference a property/field that belong to the current class.

Again, there are not many occasions when you are likely to need this, but for example you might have a local variable with the same name as a class level property/field. Then you could use this..

For example:

class MyClass
{
    string s = "1";

    void MyFunction(string s)
    {
        //s = local value as passed in to function
        //this.s = "1"
    }
}
musefan
  • 47,875
  • 21
  • 135
  • 185
1

It doesn't usually matter. The this keyword "refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method."

Check out this article.

http://msdn.microsoft.com/en-us/library/dk1507sz.aspx

trueamerican420
  • 211
  • 2
  • 10
1

As others have already pointed out, it is useful in distinguishing field/property with method variables, One other place where this is required is to invoke Extension methods on current instance. For example this.ExtensionMethod(); would work, but not just ExtensionMethod();

Other than that, its a matter of personal choice, some call it redundant and some like to use it. It totally depends on you and your team.

Personally I like to use this with class members, specially for Forms method if working on code-behind of winform, like this.Close();

For more discussion when to use this see: When do you use the "this" keyword?

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
1

generally it doesn't matter, but if you pass in a variable called, say button1, to a class method that already has a member called button1, then you'll need to disambiguate which one you really meant.

This is probably why people now use this. to explicitly say which variable you meant, if you use this practice all the time, you'll not get it wrong in the few cases where its important.

Of course, you could ensure that all member variables are uniquely named, say with a prefix like m_, but that's fallen out of fashion nowadays, people prefer to write out this.

gbjbaanb
  • 51,617
  • 12
  • 104
  • 148
1

It really depends on the situation.

http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.80).aspx

  • To qualify members hidden by similar names
  • To pass an object as a parameter to other methods
  • To declare indexers