When NOT TO USE 'this' keyword?

SMUsamaShah picture SMUsamaShah · May 15, 2010 · Viewed 7.8k times · Source

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?

Answer

Daniel Brückner picture Daniel Brückner · May 15, 2010

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.