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?
thisis almost always optional and does not need to be specified. If you want to be explicit that you are referring to a member, then usethis. 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 likethis._foo.It’s a matter of personal taste (no performance penalty), but I find having the explicit
thisis harder to maintain and adds little value if you have a solid naming convention. Some people will only usethiswhen calling a member method, e.g.this.Foo(_bar)instead ofFoo(_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.