27

Possible Duplicate:
When do you use the “this” keyword?

Hello, I understand that the This keyword is used to refer to an instance of the class, however, suppose I have a class called Life, which defines two fields, the person (their name) and their partner(their name):

class Life
{
    //Fields
    private string _person;
    private string _partner;

    //Properties
    public string Person
    {
        get { return _person; }
        set { _person = value; }
    }

    public string Partner
    {
        get { return _partner; }
        set { _partner = value; }
    }

    //Constructor 1
    public Life()
    {
        _person = "Dave";
        _partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }

    //Constructor 2
    public Life()
    {
        this._person = "Dave";
        this._partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }
}

Is there a difference between constructor 1 and constructor 2!? Or is it just better coding practice to use the "This" keyword?

Regards

Community
  • 1
  • 1
Goober
  • 13,146
  • 50
  • 126
  • 195

8 Answers8

23

The constructors are the same. The reason I would prefer the second is that it will allow you to remove the underscores from your private variable names and retain the context (improving understandability). I make it a practice to always use this when referring to instance variables and properties.

I no longer use the this keyword in this way after moving to a different company with different standards. I've gotten used to it and now rarely use it at all when referring to instance members. I do still recommend using properties (obviously).

My version of your class:

class Life
{
    //Fields
    private string person;
    private string partner;

    //Properties
    public string Person
    {
        get { return this.person; }
        set { this.person = value; }
    }

    public string Partner
    {
        get { return this.partner; }
        set { this.partner = value; }
    }


    public Life()
    {
        this.person = "Dave";
        this.partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }
}

or, even better, but not as clear about the use of this with fields.

class Life
{

    //Properties
    public string Person { get; set; }
    public string Partner { get; set; }

    public Life()
    {
        this.Person = "Dave";
        this.Partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }
}
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • So is the code i posted an older way of doing this? And is the code you posted the more updated way of doing this? Also.....Since you declare just the properties and not the fields, how is the modifier level set for the fields? or is it just automatically set as private? – Goober May 09 '09 at 13:40
  • 4
    The last example uses automatic properties introduced in C#3.0 (VS2008). Quoting from the C# Programming Guide: "In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors." Example omitted. – tvanfosson May 09 '09 at 13:52
  • I feel using the `this` keyword when redundant way to verbose and just makes the code harder to read. It should be obvious what are field and what are locals. If not, you need to break out stuff so that you have shorter methods. – vidstige Dec 03 '14 at 07:02
  • I've moved onto a different company that specifies underscores for private variables. As such, my use of `this` has changed radically. I would no longer recommend it. – tvanfosson Dec 03 '14 at 14:13
13

"this" is also used in .Net 3.5 with extension methods:

public static class MyExtensions
{    
    public static string Extend(this string text)
    {
       return text + " world";
    }
}

would extend the string class

var text = "Hello";
text.Extend();

To answer your question: no, there is no difference in your two constructors. Imo, the "this" clutters the code and should only be used when necessary, e.g. when parameters and field variables have the same names.

There is also a case when the class explicitly implements an interface. If you need to call the interface methods from within your class you would have to cast this to the interface:

class Impl : IFace
{

    public void DoStuff()
    {
        ((IFace)this).SomeMethod();
    }

    void IFace.SomeMethod()
    {
    }
}
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • Re "you beat me to it"; actually, we are showing 2 different things. I'm showing the use of "this" when **calling** an extension method - not when defining one. It is a curiosity that the "this" is necessary in such cases. – Marc Gravell May 09 '09 at 13:28
  • +1 Agree that "this" clutters the code and redundant. – Vadim May 09 '09 at 13:55
7

There is no difference in the two statements...

//These are exactly the same.

this._person 

//and 

_person 

The reference to "this" is implied in the case of _person. I wouldn't say that it is necessarily "better" coding practice, I would say that it is just preference.

Brian ONeil
  • 4,229
  • 2
  • 23
  • 25
  • Yup. There's nothing wrong with either syntax. – BlackWasp May 09 '09 at 13:28
  • 2
    I prefer the underscore syntax because it's shorter and like Brian said, the underscore implies "this" anyway. The only advantage I would say there is to explicit user of "this", is that if there's ever an ambiguity issue, "this" will resolve it. In those cases I tend to use "this" to resolve the issue at hand as a special case. – Nathan Ridley Jun 10 '09 at 08:43
3

Already discussed

When do you use the "this" keyword?

Community
  • 1
  • 1
Richard West
  • 2,166
  • 4
  • 26
  • 40
  • +1 for indicating the duplicate when no one else could find it! I was surprised this question hadn't been closed already! – Cerebrus May 09 '09 at 13:23
3

Since you are using underscores, there is no conflict between the names; so the "this." is redundant and can be omitted. The IL will be unaffected.

As long as there is no ambiguity between a field and variable/parareter, there is only one scenario in which the this keyword (in the context of meaning the current instance - not ctor-chaining) is strictly necessary - invoking an extension method that is defined separately:

this.SomeExtensionMethod();  // works
SomeExtensionMethod();  // fails
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Ah, I see it now. Curious indeed. But understandable, since extension methods are always invoked in connection with an explicit object. Without "this" it would look like you are calling a method declared in the current class. Still the compiler should be able to resolve such a method... oh well – Peter Lillevold May 09 '09 at 13:40
1

Both constructors do the same thing anyway in the second one the this is redundant

Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
0

You can use this to differentiate between a local variable named X and a class level field/property of the same name.

Richard
  • 1,169
  • 6
  • 8
0

You shouldn't be using the private variables _person and _parter. That is the purpose of your getters and setters.

As far as the constructs, there is no real difference between them. That being said, I always prefer to use the This keyword as it lends towards readability.

hmcclungiii
  • 1,765
  • 2
  • 16
  • 27