<p>I was curious about how other people use the <strong>this</strong> keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:</p>

<p>In a constructor:</p>

<pre><code>public Light(Vector v)
{
    this.dir = new Vector(v);
}
</code></pre>

<p>Elsewhere</p>

<pre><code>public void SomeMethod()
{
    Vector vec = new Vector();
    double d = (vec * vec) - (this.radius * this.radius);
}
</code></pre>

[{'answer_id': 23257, 'author': 'Thomas Owens', 'author_id': 572, 'author_profile': 'https://Stackoverflow.com/users/572', 'pm_score': 5, 'selected': False, 'text': "<p>I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.</p>\n"}, {'answer_id': 23258, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 3, 'selected': False, 'text': '<p>I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.</p>\n'}, {'answer_id': 23259, 'author': 'JamesSugrue', 'author_id': 1075, 'author_profile': 'https://Stackoverflow.com/users/1075', 'pm_score': 1, 'selected': False, 'text': "<p>I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...</p>\n"}, {'answer_id': 23260, 'author': 'juan', 'author_id': 1782, 'author_profile': 'https://Stackoverflow.com/users/1782', 'pm_score': 2, 'selected': False, 'text': "<p>You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))</p>\n"}, {'answer_id': 23264, 'author': 'Corey', 'author_id': 1595, 'author_profile': 'https://Stackoverflow.com/users/1595', 'pm_score': 7, 'selected': False, 'text': '<p>I only use it when absolutely necessary, ie, when another variable is shadowing another.  Such as here:</p>\n\n<pre><code>class Vector3\n{\n    float x;\n    float y;\n    float z;\n\n    public Vector3(float x, float y, float z)\n    {\n        this.x = x;\n        this.y = y;\n        this.z = z;\n    }\n\n}\n</code></pre>\n\n<p>Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)</p>\n'}, {'answer_id': 23267, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': 4, 'selected': False, 'text': '<p>Any time you need a reference to the current object.</p>\n\n<p>One particularly handy scenario is when your object is calling a function and wants to pass itself into it.</p>\n\n<p>Example:</p>\n\n<pre><code>void onChange()\n{\n    screen.draw(this);\n}\n</code></pre>\n'}, {'answer_id': 23278, 'author': 'akmad', 'author_id': 1314, 'author_profile': 'https://Stackoverflow.com/users/1314', 'pm_score': 1, 'selected': False, 'text': '<p>I pretty much only use <strong>this</strong> when referencing a type property from inside the same type.  As another user mentioned, I also underscore local fields so they are noticeable without needing <strong>this</strong>.</p>\n'}, {'answer_id': 23279, 'author': 'Dan Blair', 'author_id': 1327, 'author_profile': 'https://Stackoverflow.com/users/1327', 'pm_score': 0, 'selected': False, 'text': '<p>It depends on the coding standard I\'m working under.  If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.</p>\n'}, {'answer_id': 23281, 'author': 'Philippe', 'author_id': 920, 'author_profile': 'https://Stackoverflow.com/users/920', 'pm_score': 3, 'selected': False, 'text': '<p>I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.</p>\n'}, {'answer_id': 23306, 'author': 'Jason Bunting', 'author_id': 1790, 'author_profile': 'https://Stackoverflow.com/users/1790', 'pm_score': 5, 'selected': False, 'text': '<p>I can\'t believe all of the people that say using it always is a "best practice" and such.</p>\n\n<p>Use "this" when there is ambiguity, as in <a href="https://stackoverflow.com/a/23264/282110">Corey\'s example</a> or when you need to pass the object as a parameter, as in <a href="https://stackoverflow.com/a/23267/282110">Ryan\'s example</a>. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.</p>\n\n<p>EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - <a href="http://msdn.microsoft.com/en-us/library/dk1507sz(VS.71).aspx" rel="nofollow noreferrer">for declaring indexers</a></p>\n\n<p>EDIT: @Juan: Huh, I don\'t see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually <em>need</em> it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.</p>\n'}, {'answer_id': 23323, 'author': 'Stu', 'author_id': 414, 'author_profile': 'https://Stackoverflow.com/users/414', 'pm_score': -1, 'selected': False, 'text': '<p>Never. Ever. If you have variable shadowing, your naming conventions are on crack. I mean, really, no distinguishing naming for member variables? <em>Facepalm</em></p>\n'}, {'answer_id': 23340, 'author': 'Ian Nelson', 'author_id': 2084, 'author_profile': 'https://Stackoverflow.com/users/2084', 'pm_score': 5, 'selected': False, 'text': '<p>I use it whenever <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="noreferrer">StyleCop</a> tells me to. <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="noreferrer">StyleCop</a> must be obeyed. Oh yes.</p>\n'}, {'answer_id': 23435, 'author': 'Scott Wisniewski', 'author_id': 1737192, 'author_profile': 'https://Stackoverflow.com/users/1737192', 'pm_score': 8, 'selected': False, 'text': '<p>I don\'t mean this to sound snarky, but it doesn\'t matter.</p>\n\n<p>Seriously.</p>\n\n<p>Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It\'s not going to reduce bugs, it\'s not going to have any appreciable effect on code quality or maintainability. It\'s not going to get you a raise, or allow you to spend less time at the office. </p>\n\n<p>It\'s really just a style issue. If you like "this", then use it. If you don\'t, then don\'t. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer\'s notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn\'t like, or would have done differently. At some point some guy is going to read your code and grumble about something. </p>\n\n<p>I wouldn\'t fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn\'t going to be scrutinizing how you initialize fields. He\'s just going to use your code, marvel at it\'s greatness, and then move on to something else.</p>\n'}, {'answer_id': 23502, 'author': 'Jakub Šturc', 'author_id': 2361, 'author_profile': 'https://Stackoverflow.com/users/2361', 'pm_score': 9, 'selected': True, 'text': '<p>There are several usages of <a href="http://msdn.microsoft.com/en-us/library/dk1507sz.aspx" rel="noreferrer">this</a> keyword in C#.</p>\n\n<ol>\n<li><a href="http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx" rel="noreferrer">To qualify members hidden by similar name</a></li>\n<li><a href="http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx" rel="noreferrer">To have an object pass itself as a parameter to other methods</a></li>\n<li>To have an object return itself from a method</li>\n<li><a href="http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx" rel="noreferrer">To declare indexers</a></li>\n<li><a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx" rel="noreferrer">To declare extension methods</a></li>\n<li><a href="http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C%29" rel="noreferrer">To pass parameters between constructors</a></li>\n<li><a href="https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/1800162#1800162">To internally reassign value type (struct) value</a>.</li>\n<li>To invoke an extension method on the current instance</li>\n<li>To cast itself to another type</li>\n<li><a href="https://stackoverflow.com/questions/1814953/c-sharp-constructor-chaining-how-to-do-it">To chain constructors defined in the same class</a></li>\n</ol>\n\n<p>You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using <a href="https://msdn.microsoft.com/en-us/library/bb384054.aspx" rel="noreferrer">auto-implemented properties</a>.</p>\n'}, {'answer_id': 23520, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 2, 'selected': False, 'text': "<p>Here's when I use it:</p>\n\n<ul>\n<li>Accessing Private Methods from within the class (to differentiate)</li>\n<li>Passing the current object to another method (or as a sender object, in case of an event)</li>\n<li>When creating extension methods :D</li>\n</ul>\n\n<p>I don't use this for Private fields because I prefix private field variable names with an underscore (_). </p>\n"}, {'answer_id': 24003, 'author': 'Brandon Wood', 'author_id': 423, 'author_profile': 'https://Stackoverflow.com/users/423', 'pm_score': 6, 'selected': False, 'text': "<p>Personally, I try to always use <em>this</em> when referring to member variables.  It helps clarify the code and make it more readable.  Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see <em>this</em> used consistently, they will know if they are looking at a member variable or not.</p>\n"}, {'answer_id': 27246, 'author': 'JohnMcG', 'author_id': 1674, 'author_profile': 'https://Stackoverflow.com/users/1674', 'pm_score': 2, 'selected': False, 'text': "<p>I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)</p>\n\n<p>But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.</p>\n"}, {'answer_id': 28679, 'author': 'Nick', 'author_id': 1236, 'author_profile': 'https://Stackoverflow.com/users/1236', 'pm_score': 2, 'selected': False, 'text': '<p>[C++]</p>\n\n<p>I agree with the "use it when you have to" brigade. Decorating code unnecessarily with <em>this</em> isn\'t a great idea because the compiler won\'t warn you when you forget to do it. This introduces potential confusion for people expecting <em>this</em> to always be there, i.e. they\'ll have to <em>think</em> about it.</p>\n\n<p>So, when would you use it? I\'ve just had a look around some random code and found these examples (I\'m not passing judgement on whether these are <em>good</em> things to do or otherwise):</p>\n\n<ul>\n<li>Passing "yourself" to a function.</li>\n<li>Assigning "yourself" to a pointer or something like that.</li>\n<li>Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.</li>\n<li>Compiler enforced disambiguation.</li>\n</ul>\n'}, {'answer_id': 39993, 'author': 'dicroce', 'author_id': 3886, 'author_profile': 'https://Stackoverflow.com/users/3886', 'pm_score': -1, 'selected': False, 'text': '<p>You should not use "this" unless you absolutely must.</p>\n\n<p>There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.</p>\n'}, {'answer_id': 47397, 'author': 'Pete Kirkham', 'author_id': 1527, 'author_profile': 'https://Stackoverflow.com/users/1527', 'pm_score': 1, 'selected': False, 'text': '<p>I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:</p>\n\n<pre><code>boolean sameValue (SomeNum other) {\n   return this.importantValue == other.importantValue;\n} \n</code></pre>\n'}, {'answer_id': 70058, 'author': 'Stacker', 'author_id': 6574, 'author_profile': 'https://Stackoverflow.com/users/6574', 'pm_score': 1, 'selected': False, 'text': '<p><strong>[C++]</strong></p>\n\n<p><em>this</em> is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:</p>\n\n<pre><code>A a;\na = a;\n</code></pre>\n\n<p>Your assignment operator will be written:</p>\n\n<pre><code>A&amp; A::operator=(const A&amp; a) {\n    if (this == &amp;a) return *this;\n\n    // we know both sides of the = operator are different, do something...\n\n    return *this;\n}\n</code></pre>\n'}, {'answer_id': 104938, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 1, 'selected': False, 'text': '<h2><code>this</code> on a C++ compiler</h2>\n\n<p>The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:</p>\n\n<ul>\n<li>using the mother class\' method if you did not overloaded it in the child class.</li>\n<li>promoting a value of a type into another type</li>\n</ul>\n\n<p>But sometimes, <strong>You just don\'t want the compiler to guess. You want the compiler to pick-up the right symbol and not another.</strong></p>\n\n<p><strong>For me</strong>, those times are when, within a method, I want to access to a member method or member variable. I just don\'t want some random symbol picked up just because I wrote <code>printf</code> instead of <code>print</code>. <code>this->printf</code> would not have compiled.</p>\n\n<p>The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.</p>\n\n<p>These are the reasons I use <code>this</code>.</p>\n\n<p>(§) it\'s still a kind of mystery to me, but I now wonder if the fact you include the &lt;windows.h&gt; header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace</p>\n\n<p>(§§) realizing that "you need to include a header, but that including this header will break  your code because it uses some dumb macro with a generic name" is one of those <a href="http://en.wikipedia.org/wiki/Russian_roulette" rel="nofollow noreferrer">russian roulette</a> moments of a coder\'s life</p>\n'}, {'answer_id': 105015, 'author': 'Paul Batum', 'author_id': 48281, 'author_profile': 'https://Stackoverflow.com/users/48281', 'pm_score': 3, 'selected': False, 'text': "<p>Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:</p>\n\n<pre><code>class Example : ICloneable\n{\n    private void CallClone()\n    {\n        object clone = ((ICloneable)this).Clone();\n    }\n\n    object ICloneable.Clone()\n    {\n        throw new NotImplementedException();\n    }\n}\n</code></pre>\n"}, {'answer_id': 105016, 'author': 'Cyberherbalist', 'author_id': 16964, 'author_profile': 'https://Stackoverflow.com/users/16964', 'pm_score': 2, 'selected': False, 'text': "<p>In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of <code>this</code> is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.</p>\n\n<pre><code>class MyClass {\n    private int _x\n    public MyClass() : this(5) {}\n    public MyClass(int v) { _x = v;}\n}\n</code></pre>\n\n<p>I've found this to be a particularly useful feature on occasion.</p>\n"}, {'answer_id': 105112, 'author': 'Mark Ransom', 'author_id': 5987, 'author_profile': 'https://Stackoverflow.com/users/5987', 'pm_score': 0, 'selected': False, 'text': '<p>I use it to invoke <strong>Intellisense</strong> just like <a href="https://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword#27246">JohnMcG</a>, but I\'ll go back and erase "this->" when I\'m done.  I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.</p>\n'}, {'answer_id': 107010, 'author': 'slim', 'author_id': 7512, 'author_profile': 'https://Stackoverflow.com/users/7512', 'pm_score': 0, 'selected': False, 'text': '<p>1 - Common Java setter idiom:</p>\n\n<pre><code> public void setFoo(int foo) {\n     this.foo = foo;\n }\n</code></pre>\n\n<p>2 - When calling a function with this object as a parameter</p>\n\n<pre><code>notifier.addListener(this);\n</code></pre>\n'}, {'answer_id': 650055, 'author': 'Jonathan C Dickinson', 'author_id': 24064, 'author_profile': 'https://Stackoverflow.com/users/24064', 'pm_score': 1, 'selected': False, 'text': "<p>'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).</p>\n\n<p>Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.</p>\n\n<p>I usually delete it once I have what I was after: but this is just my style breaking through.</p>\n\n<p>In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.</p>\n"}, {'answer_id': 783056, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I use it every time I can.  I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.</p>\n'}, {'answer_id': 783345, 'author': 'Paw Baltzersen', 'author_id': 94923, 'author_profile': 'https://Stackoverflow.com/users/94923', 'pm_score': 1, 'selected': False, 'text': "<p>When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.</p>\n\n<p>To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.</p>\n"}, {'answer_id': 2182664, 'author': 'David Rodríguez - dribeas', 'author_id': 36565, 'author_profile': 'https://Stackoverflow.com/users/36565', 'pm_score': 0, 'selected': False, 'text': '<p>There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.</p>\n\n<p>You can use <code>this</code> to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct base {\n   void f() {}\n};\n\ntemplate &lt;typename T&gt;\nstruct derived : public base&lt;T&gt;\n{\n   void test() {\n      //f(); // [1] error\n      base&lt;T&gt;::f(); // quite verbose if there is more than one argument, but valid\n      this-&gt;f(); // f is now an argument dependent symbol\n   }\n}\n</code></pre>\n\n<p>Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments. </p>\n\n<p>At that step, without actually substituting the type, the compiler has almost no information of what <code>base&lt;T&gt;</code> could be (note that specialization  of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call <code>f</code> that seems just natural to the programmer is a symbol that the compiler must find as a member of <code>derived</code> or in enclosing namespaces --which does not happen in the example-- and it will complain.</p>\n\n<p>The solution is turning the non-dependent name <code>f</code> into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (<code>base&lt;T&gt;::f</code> --adding the <code>base&lt;T&gt;</code> makes the symbol dependent on <code>T</code> and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.</p>\n\n<p>The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a <code>this-&gt;</code> before the symbol. As the template class you are implementing does depend on an argument (it inherits from <code>base&lt;T&gt;</code>) <code>this-&gt;</code> is argument dependent, and we get the same result: <code>this-&gt;f</code> is checked in the second round, after template parameter substitution.</p>\n'}, {'answer_id': 2789224, 'author': 'bobobobo', 'author_id': 111307, 'author_profile': 'https://Stackoverflow.com/users/111307', 'pm_score': 2, 'selected': False, 'text': "<p>I use it when, in a function that accepts a reference to an object of the same type, I want to make it <strong>perfectly clear</strong> which object I'm referring to, where.</p>\n\n<p>For example</p>\n\n<pre><code>class AABB\n{\n  // ... members\n  bool intersects( AABB other )\n  {\n    return other.left() &lt; this-&gt;right() &amp;&amp;\n           this-&gt;left() &lt; other.right() &amp;&amp;\n\n           // +y increases going down\n           other.top() &lt; this-&gt;bottom() &amp;&amp;\n           this-&gt;top() &lt; other.bottom() ;\n  }\n} ;\n</code></pre>\n\n<p>(vs)</p>\n\n<pre><code>class AABB\n{\n  bool intersects( AABB other )\n  {\n    return other.left() &lt; right() &amp;&amp;\n           left() &lt; other.right() &amp;&amp;\n\n           // +y increases going down\n           other.top() &lt; bottom() &amp;&amp;\n           top() &lt; other.bottom() ;\n  }\n} ;\n</code></pre>\n\n<p>At a glance which AABB does <code>right()</code> refer to?  The <code>this</code> adds a bit of a clarifier.</p>\n"}]
['https://Stackoverflow.com/questions/23250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016/']