248

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

In a constructor:

public Light(Vector v)
{
    this.dir = new Vector(v);
}

Elsewhere

public void SomeMethod()
{
    Vector vec = new Vector();
    double d = (vec * vec) - (this.radius * this.radius);
}
Venkat
  • 2,549
  • 2
  • 28
  • 61
ftdysa
  • 1,242
  • 6
  • 17
  • 26
  • 2
    I found good examples when you **really need** `this` at MSDN. Please follow [this link](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz(v=vs.100).aspx) ... ;-) – Matt Feb 18 '14 at 08:38
  • 12
    If you have to understand and optimize or rewrite someone else, mostly poorly written code you would be happy to have `this` or any other qualifier so that from a simple look you know the scope of the variable (Especially omitted class qualifiers for constants (same package or hierarchy) or `super`/`base` qualifiers). And using the commonly used syntax like `_foo` does not seems that elegant for myself. Pressing `_` for intellisense is more time consuming than entering `this`. And why bother at all! With eclipse auto-save formatting functions no need for `_` in case you forgot the qualifier. – djmj May 29 '14 at 15:20
  • After reading the answers and comments below, as well as reading the MSDN documentation: https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/dk1507sz(v=vs.100) on the **this** keyword that hasn't been updated in 6 years, I would suggest to not ever use the **this** keyword. It's pointless. Don't make parameters the same name, that's confusing and stupid. Why would you do that? Also, don't pass the instance in using **this**, it's also confusing and stupid. – Yusha Jul 10 '19 at 18:35

31 Answers31

245

I don't mean this to sound snarky, but it doesn't matter.

Seriously.

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.

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.

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.

Nick
  • 25,026
  • 7
  • 51
  • 83
Scott Wisniewski
  • 24,561
  • 8
  • 60
  • 89
  • 35
    The `this` keyword is semantically meaningful. See @JasonBunting's comment below. You confuse the stylistic overuse of `this` with its actual purpose. Your remark isn't just flippant, it's wrong! – Dan Barowy Jun 04 '13 at 16:43
  • 12
    If you get a chance, you might want to re-read my answer. I talk about using it in the cases where it is necessary for the correct semantics. You might also want to look at the origin question. It's showing the use in examples where it is not semantically necessary. So, I'm not sure exactly what I said that was "wrong". My answer is certainly not flippant. – Scott Wisniewski Jun 05 '13 at 02:12
  • 9
    Do you know how your answer sounds to me? Between the lines I read "How do you dare to ask a question like this?" - That is really not constructive in my opinion. No one knows everything - this is why we have Stackoverflow: To help out others and to get help. Some topics you know, some know others. Help each other, do not fight with each other. Please think about it. – Matt Feb 05 '14 at 10:00
  • 9
    I don't mean to sound snarky, but this is one of the worst answers so far. I don't see how comparing this to your job or personal life is useful. Just because some things are less important than others doesn't mean that they are *unimportant*. Having a consistent programming style is not unimportant (read a book on code readability/maintainability of your choice). – aioobe Mar 15 '15 at 07:51
  • *[...] every programmer has his own unique programing style [...]* If this is the case in your project, you're in great need of a project wide style guideline document. Whether or not these guidelines advocate the use of `this` in the situation described by OP matters little, but *don't* neglect the importance of following these guidelines and keeping the code consistent. – aioobe Mar 15 '15 at 07:52
  • 4
    I think you may have misunderstood my point. It was not that "having a consistent style" is bad. I say nothing to that effect. It's that the op question of "should my style guide mandate 'this.' as a prefix for all field accesses?" is arbitrary and capricious. – Scott Wisniewski Mar 15 '15 at 19:20
  • 2
    Actually, neither you nor OP mention style guides. In fact, you say *"If you like "this", then use it. If you don't, then don't."* and *"every programmer has his own unique programing style"*. This answer keeps getting worse every time I read it. I think you should face the fact that it has 18 downvotes and consider a complete rewrite (although it wouldn't be fair to those already voted) or delete it. – aioobe Mar 16 '15 at 07:51
  • It's easily to agree with you, but there are a lot of coding conventions, guidelines, standards in direction of code quality and/or readability that can define the use of language keywords is meaninful, and prevent what you called personal aesthetically pleasing code. – m.rufca Jun 08 '17 at 19:27
  • What a great comment @ScottWisniewski you've summed it up perfectly. – Jon Sep 26 '19 at 18:09
217

There are several usages of this keyword in C#.

  1. To qualify members hidden by similar name
  2. To have an object pass itself as a parameter to other methods
  3. To have an object return itself from a method
  4. To declare indexers
  5. To declare extension methods
  6. To pass parameters between constructors
  7. To internally reassign value type (struct) value.
  8. To invoke an extension method on the current instance
  9. To cast itself to another type
  10. To chain constructors defined in the same class

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 auto-implemented properties.

Community
  • 1
  • 1
Jakub Šturc
  • 35,201
  • 25
  • 90
  • 110
  • 49
    8. To invoke an extension method on the current instance (`this.Foo();` will work, but `Foo()` will not) – Marc Gravell Nov 17 '11 at 13:20
  • 4
    Also to cast itself to another type, for example an explicitly implemented method will be called like `((ICollection)this).Add(bla)`. – nawfal Nov 13 '13 at 18:02
  • 4
    To chain construction to another constructor defined in the same type. `public ClassName(...) : this(...)`. – Lasse V. Karlsen Jul 04 '14 at 20:34
  • If I use 'this' keyword many times, will it reduce performance ? – Kira Oct 28 '14 at 11:40
  • @Anand: Create a separate question please. Nevertheless please be more specific what usage of this keyword you have in mind. – Jakub Šturc Nov 04 '14 at 13:05
  • 1
    @Anand it will not affect performance at run time whatsoever. Assuming there is no ambiguity, the compiler's output is the same regardless of whether you write, for example `this.someField = someValue` or `someField = someValue`. It could affect the compiler's performance, since the compiler will parse the source code differently, but any difference would surely be negligible. – phoog May 05 '15 at 20:58
  • 7
    You can avoid the first issue by accessing fields through properties *only if you adhere to a style convention whereby properties cannot have the same names as parameters.* It just happens that the prevalent C# style convention meets that requirement. Not all C# is written under that convention, however. There's nothing inherent about properties per se that would make the `this` keyword unnecessary; a constructor parameter called `x` will hide a member called `x` whether the member is a field, a property, or an event, for that matter. – phoog May 05 '15 at 21:04
96

I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:

class Vector3
{
    float x;
    float y;
    float z;

    public Vector3(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

}

Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)

Ali Raza
  • 79
  • 1
  • 4
Corey
  • 14,101
  • 7
  • 38
  • 35
54

Personally, I try to always use this 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 this used consistently, they will know if they are looking at a member variable or not.

Brandon Wood
  • 5,347
  • 4
  • 38
  • 31
  • 9
    but if you forget to use it sometime, they will get confused – surfen Dec 04 '11 at 00:21
  • 2
    @surfen that can be avoided by additional style checks, e.g. in Java you can use Checkstyle and run it after a full build (and in any popular iterative/OO language there will be similar tools) – Maarten Bodewes Jan 08 '14 at 12:01
  • 5
    @surfen as if you forget it in ambiguous cases. I can break any argument by saying "but if you forget...". – Askolein Jan 21 '14 at 12:49
  • @Askolein You know save-action auto-formatting IDE functionality? There is no argument "but if you forget" – djmj May 29 '14 at 15:24
  • 6
    Most people seem to never read, optimize or rewrite someone else's code! Qualifiers are time and motivation saver! Without qualifier its like magic if you see any arbitrary line of code. So you waste all time just checkin where these variables come from. – djmj May 29 '14 at 15:26
  • 3
    I know this is a very old post, but just cannot help but comment on the irony of this answer (which I happen to agree with). In the Jihad against the evil Hungarian Notation, anyone who dared prefix their member variables with "m_" was quickly pilloried because distinguishing member variables was just not useful or needed. – Michael J. Nov 04 '16 at 14:25
  • @MichaelJ. - "...distinguishing member variables was just not useful or needed" What do you think prefacing them with "this." is?! It's distinguishing a member variable. And "m_" isn't Hungarian notation. Hungarian notation is typically 3 character abbreviation of a variables _type_, not its scope. Quite different. – Jason Bunting Jul 23 '19 at 22:23
38

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.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
  • I want to distinct class variables as much as I can, so code is more clear. I used to use prefix m_ (member variable) e.g. private string m_name. Now I just use this e.g. if i have class Test { private string a; public someMethod() { this.a = "foo"; } } – broadband Jan 10 '14 at 11:17
36

I can't believe all of the people that say using it always is a "best practice" and such.

Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. 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.

EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers

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 need 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.

Community
  • 1
  • 1
Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
  • 21
    @[JasonBunting](http://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword#23306): You can't do something sometimes and not some others... it's confusing... ***I*** hope I never work in ***your*** code You can't always asume that a person who reads your code in the future will understand what you wrote, you need to be as clear as possible, and one way to achieve it is to be consistent – juan Aug 22 '08 at 19:51
  • @juan, 10 years latter. You still think using "this" is good practice? :) – Scott Adams Jun 19 '19 at 03:19
  • 2
    @ScottAdams I still believe in consistency and clarity, yes – juan Jun 19 '19 at 13:10
  • What about determining the scope of a variable (whether it's local or a member variable) just by looking at it? Isn't 'this' justified for this purpose? Or you mean to say that if we write smaller methods it'd be easy enough to understand the scope of the variable anyway? – BornToCode Jun 26 '19 at 09:45
27

I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.

Ian Nelson
  • 57,123
  • 20
  • 76
  • 103
  • 1
    And ReSharper tells me not to use it. Kind of confusing when I'm using both StyleCop and ReSharper at the same time :) But I lean to Coreys answer above, to use 'this' keyword only when absolutely necessary. – Gunnar May 24 '13 at 11:55
  • @Gunnar, there's an option to disable getting rid of redundant "this." in R# – wingerse Feb 26 '16 at 20:56
  • @EmperorAiman - Yes, I know. My point was that those two popular formatting tools are by default, suggesting two different things and that can be confusing. "To be or not to be..." :) – Gunnar Apr 26 '16 at 11:17
11

Any time you need a reference to the current object.

One particularly handy scenario is when your object is calling a function and wants to pass itself into it.

Example:

void onChange()
{
    screen.draw(this);
}
Ryan Fox
  • 10,103
  • 5
  • 38
  • 48
7

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.

Philippe
  • 3,945
  • 3
  • 38
  • 56
5

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:

class Example : ICloneable
{
    private void CallClone()
    {
        object clone = ((ICloneable)this).Clone();
    }

    object ICloneable.Clone()
    {
        throw new NotImplementedException();
    }
}
Paul Batum
  • 8,165
  • 5
  • 40
  • 45
5

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.

TheSmurf
  • 15,337
  • 3
  • 40
  • 48
4

Here's when I use it:

  • Accessing Private Methods from within the class (to differentiate)
  • Passing the current object to another method (or as a sender object, in case of an event)
  • When creating extension methods :D

I don't use this for Private fields because I prefix private field variable names with an underscore (_).

Vaibhav
  • 11,310
  • 11
  • 51
  • 70
4

[C++]

I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this 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 this to always be there, i.e. they'll have to think about it.

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 good things to do or otherwise):

  • Passing "yourself" to a function.
  • Assigning "yourself" to a pointer or something like that.
  • Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
  • Compiler enforced disambiguation.
Nick
  • 761
  • 4
  • 9
3

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 this is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.

class MyClass {
    private int _x
    public MyClass() : this(5) {}
    public MyClass(int v) { _x = v;}
}

I've found this to be a particularly useful feature on occasion.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cyberherbalist
  • 12,061
  • 17
  • 83
  • 121
3

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))

juan
  • 80,295
  • 52
  • 162
  • 195
3

I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.

For example

class AABB
{
  // ... members
  bool intersects( AABB other )
  {
    return other.left() < this->right() &&
           this->left() < other.right() &&

           // +y increases going down
           other.top() < this->bottom() &&
           this->top() < other.bottom() ;
  }
} ;

(vs)

class AABB
{
  bool intersects( AABB other )
  {
    return other.left() < right() &&
           left() < other.right() &&

           // +y increases going down
           other.top() < bottom() &&
           top() < other.bottom() ;
  }
} ;

At a glance which AABB does right() refer to? The this adds a bit of a clarifier.

bobobobo
  • 64,917
  • 62
  • 258
  • 363
2

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)

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.

JohnMcG
  • 8,709
  • 6
  • 42
  • 49
1

this on a C++ compiler

The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:

  • using the mother class' method if you did not overloaded it in the child class.
  • promoting a value of a type into another type

But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.

For me, 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 printf instead of print. this->printf would not have compiled.

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.

These are the reasons I use this.

(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace

(§§) 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 russian roulette moments of a coder's life

paercebal
  • 81,378
  • 38
  • 130
  • 159
1

I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...

JamesSugrue
  • 14,891
  • 10
  • 61
  • 93
1

I pretty much only use this 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 this.

akmad
  • 19,343
  • 2
  • 29
  • 25
1

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:

boolean sameValue (SomeNum other) {
   return this.importantValue == other.importantValue;
} 
Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
1

'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).

Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.

I usually delete it once I have what I was after: but this is just my style breaking through.

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.

Jonathan C Dickinson
  • 7,181
  • 4
  • 35
  • 46
1

[C++]

this 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:

A a;
a = a;

Your assignment operator will be written:

A& A::operator=(const A& a) {
    if (this == &a) return *this;

    // we know both sides of the = operator are different, do something...

    return *this;
}
Stacker
  • 111
  • 2
1

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.

1

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.

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.

Paw Baltzersen
  • 2,662
  • 3
  • 24
  • 33
0

I use it to invoke Intellisense just like JohnMcG, 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.

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

1 - Common Java setter idiom:

 public void setFoo(int foo) {
     this.foo = foo;
 }

2 - When calling a function with this object as a parameter

notifier.addListener(this);
slim
  • 40,215
  • 13
  • 94
  • 127
0

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.

You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.

template <typename T>
struct base {
   void f() {}
};

template <typename T>
struct derived : public base<T>
{
   void test() {
      //f(); // [1] error
      base<T>::f(); // quite verbose if there is more than one argument, but valid
      this->f(); // f is now an argument dependent symbol
   }
}

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.

At that step, without actually substituting the type, the compiler has almost no information of what base<T> 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 f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.

The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.

The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

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.

Dan Blair
  • 2,399
  • 3
  • 21
  • 32
-2

You should not use "this" unless you absolutely must.

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.

dicroce
  • 45,396
  • 28
  • 101
  • 140
-8

Never. Ever. If you have variable shadowing, your naming conventions are on crack. I mean, really, no distinguishing naming for member variables? Facepalm

Stu
  • 15,675
  • 4
  • 43
  • 74