15

Sorry for asking it again, there are already some questions about this keyword. But all of them tell the purpose of 'this'.

When do you use this keyword
C# when to use this keyword
Use of “this” keyword in formal parameters for static methods in C#
Proper usage of “this.” keyword in C#?

My question is when not to use 'this' keyword .
OR
Is it all right to use this keyword always in situation like the code

class RssReader
{
    private XmlTextReader _rssReader;
    private XmlDocument _rssDoc;
    private XmlNodeList _xn;

    protected XmlNodeList Item { get { return _xn; } }
    public int Count { get { return _count; } }

    public bool FetchFeed(String url)
    {
        this._rssReader = new XmlTextReader(url);
        this._rssDoc = new XmlDocument();
        _rssDoc.Load(_rssReader);
        _xn = _rssDoc.SelectNodes("/rss/channel/item");
        _count = _xn.Count;
        return true;
    }
}

here i have not used 'this' with "_xn" and "_count" also not with "_rssDoc.Load(_rssReader);" is it fine? Should i use "this" with all occurrences of class variables within the class?

Edit: Is it useless to use 'this' in a class for its own variables?

Community
  • 1
  • 1
SMUsamaShah
  • 7,677
  • 22
  • 88
  • 131
  • 2
    Despite the __NOT__, this is a duplicate of a duplicate of a possible duplicate of [C# When To Use "This" Keyword](http://stackoverflow.com/questions/843288/c-when-to-use-this-keyword) – H H May 15 '10 at 21:46
  • 1
    possible duplicate of [When do you use the "this" keyword?](http://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword) – ChrisF May 15 '10 at 21:53
  • I told in the beginning that "Sorry for asking it again, there are already 3 questions about this keyword" – SMUsamaShah May 15 '10 at 21:55
  • It is about the same thing, but question is different – SMUsamaShah May 15 '10 at 21:57
  • If you really think this isn't a duplicate, then you should at least link to the other 3 questions. – Christian Payne May 16 '10 at 00:09

12 Answers12

25

I always use this. I use the same naming convention for local variables and private fields and it makes the code much easier to read because it becomes obvious if the used identifier is a field or local variable.

Further it prevents the introduction of bugs by adding a new local variable that hides a field.

internal sealed class Foo
{
    private Int32 bar = 42;

    private void Bar()
    {
        // Uncommenting the following line will change the
        // semantics of the method and probably introduce
        // a bug.  
        //var bar = 123;

        Console.WriteLine(bar);

        // This statement will not be affected.
        Console.WriteLine(this.bar);
    }
}

This can be avoided by using different naming conventions for fields and local variables but I really dislike underscore prefixed names. The first character of a word is very important for its readability and an underscore is one of the worst possible choices.

Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143
  • 2
    Personally I like the underscore because it's a pain to type and looks ugly. It reminds me to encapsulate fields and go through property accessors whenever possible, even within the class. And "this." is just five characters I don't have to type. – TrueWill May 15 '10 at 22:39
  • @BrianOrtiz for using a language that is so oriented at idiot proofing I don't get why people don't want to write 5 chars. I'm happy with Python and Js forcing the reference to the instance tbh. – Alvaro Aug 23 '16 at 14:12
18

this is almost always optional and does not need to be specified. If you want to be explicit that you are referring to a member, then use this. If you have a naming convention (such as naming all member fields something like _foo), then you really don't need to refer to them like this._foo.

It's a matter of personal taste (no performance penalty), but I find having the explicit this is harder to maintain and adds little value if you have a solid naming convention. Some people will only use this when calling a member method, e.g. this.Foo(_bar) instead of Foo(_bar), but again, I don't personally believe it adds much.

If you're working with existing code, follow the convention there, otherwise, pick whichever makes you the most productive and effective.

Chris Schmich
  • 29,128
  • 5
  • 77
  • 94
14

My rule of thumb: Never use 'this' when it is redundant. In this case, 'this' is redundant, so I would avoid it. A tool like ReSharper is very good at telling you when this is the case.

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
  • I have downloaded it but not tried yet. And yes, redundancy looks odd. Can i assume that using this within a class for its variables is useless because it has no effect? – SMUsamaShah May 15 '10 at 21:32
  • Yes, that is a proper assumption. If a member car has the same name as a car in your scope, you must use 'this' to disambiguate. You also need it for constructor chaining, extension methods and a few other subtle cases. – Brian Genisio May 29 '10 at 00:54
  • I only use this when I'm writing code wrapped in a region for a block that's a 1000 lines long. – Ritch Melton Mar 14 '11 at 19:39
9

I always use this. to make it clear that I am referring to a class member, not a local variable.

recursive
  • 83,943
  • 34
  • 151
  • 241
3

I would try to be consistent, so that people don't get confused into thinking that the few you do the other way (apart from the way you normally pick) have some special significance.

If you don't use the _whatever naming convention for fields, then you should use this.whatever consistently because otherwise there will be problems when constructors take a whatever parameter and try to put in a whatever field.

Doug McClean
  • 14,265
  • 6
  • 48
  • 70
3

It is fine. Especially since your class doesn't have a base class and the private fields are named appropriately. ReSharper considers this in your case to be redundant.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
3

Should i use "this" with all occurrences of class variables within the class?

In your particular case, NO.

Consider however the following example:

class RssReader
{
    private String url;

    public bool FetchFeed (String url)
    {
        new XmlTextReader (url);

        // vs.

        new XmlTextReader (this.url);

        return true;
    }
}

Here you'll need to specify this to access the instance variable that has the same name as the method argument.

3

there is absolutely no reason not to use this. even redundancy is no reason not to use it, at all. You get the benefit of the intellisense box to safely complete your code and saves your time by selecting the right variable with the down-key and not to maul your keyboard all the time.

OlimilOops
  • 6,747
  • 6
  • 26
  • 36
2

You may, but don't need to unless it's a method that takes arguments with the same names as your class vars (to distinguish them).

mingos
  • 23,778
  • 12
  • 70
  • 107
1

Here is how I look at it. When you call a member (be it method, property or field) of a class as such like DoMyThing(); or return Property; within the instance scope, it's not necessary that you're calling an instance member. DoMyThing or Property can be static members too.

public class Abc
{
    public static void Static()
    {
    }

    public Xyz Instance;

    public void Test() //instance scope
    {
        var xyz = Instance; //calls instance member
        Static(); //calls static member
    }
}

For both of them (static and instance) I've not prefixed anything. Actually my choices are:

  1. do not prefix at all as above

    public void Test()
    {
        var xyz = Instance;
        Static();
    }
    
  2. prefix for instance members alone

    public void Test()
    {
        var xyz = this.Instance; // prefixes 'this'
        Static(); 
    }
    
  3. prefix for static members alone

    public void Test()
    {
        var xyz = Instance; 
        Abc.Static(); //prefixes class
    }
    
  4. prefix in both cases

    public void Test()
    {
        var xyz = this.Instance; // prefixes 'this'
        Abc.Static(); //prefixes class
    }
    

This answer is not to say one style is better than other. This is just personal preference. Each has its own claim for correctness and readability.

My take:

a. I for one do not like the inconsistent style of 2. and 3.

b. 1. has the advantage of being more readable for me. Prefixing makes it more about definition than intent.

c. 4. is all about correctness. It has the advantage of being extremely consistent, especially considering you would be forced to prefix for both instance and static members at some point anyway. This is even more important to consider when it comes to base keyword where if you dont prefix with base keyword for a base class member, then adding a member with the same name in current derived class will cause it to override the previous call, changing the whole dynamics.

Personally, I would go with 1. And use this or Abc sparingly when I'm forced to. It's more readable for me, a benefit for me that is good enough to compensate for the little inconsistency it might cause.

Community
  • 1
  • 1
nawfal
  • 70,104
  • 56
  • 326
  • 368
1

Well, as for me, 'this' looks really redundant when used with names starting with "_". This is absolutely legal in your example though.

n535
  • 4,983
  • 4
  • 23
  • 28
0

Whereas your code will work without ‘this’, it explicitly tells that you mean ‘this’ particular instance of the class. Some people find it easier to read, plus it can help avoid mistakes.

Imagine you made a mistake and wrote…

public string Name
  { get; private set; }

public Forest(string name)
  {
    name = Name;   //these are written in the wrong order...
  }

It’s an easy mistake to make given that it’s essentially the same word. Unfortunately the compiler will not catch it - it won’t throw an error. As a result your instance will be created but the property will not have its value assigned. On the other hand if you made the same mistake while using ‘this’…

public string Name
  { get; private set; }

public Forest(string name)
  {
    this.name = Name;   //these are still  written in the wrong order but with 'this' prefix...
  }

the compiler will throw an error telling you that you are attempting to assign value to a non existent property.