When do you use the "this" keyword?

214,490

Solution 1

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.

Solution 2

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.

Solution 3

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)

Solution 4

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.

Solution 5

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.

Share:
214,490

Related videos on Youtube

riffraff
Author by

riffraff

Updated on October 12, 2020

Comments

  • riffraff
    riffraff over 3 years

    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);
    }
    
    • Matt
      Matt over 10 years
      I found good examples when you really need this at MSDN. Please follow this link ... ;-)
    • djmj
      djmj about 10 years
      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.
    • Yusha
      Yusha almost 5 years
      After reading the answers and comments below, as well as reading the MSDN documentation: docs.microsoft.com/en-us/previous-versions/visualstudio/… 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.
  • juan
    juan almost 16 years
    @JasonBunting: 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
  • Marc Gravell
    Marc Gravell over 12 years
    8. To invoke an extension method on the current instance (this.Foo(); will work, but Foo() will not)
  • surfen
    surfen over 12 years
    but if you forget to use it sometime, they will get confused
  • Gunnar
    Gunnar about 11 years
    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.
  • Dan Barowy
    Dan Barowy about 11 years
    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!
  • Scott Wisniewski
    Scott Wisniewski about 11 years
    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.
  • nawfal
    nawfal over 10 years
    Also to cast itself to another type, for example an explicitly implemented method will be called like ((ICollection<T>)this).Add(bla).
  • Maarten Bodewes
    Maarten Bodewes over 10 years
    @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)
  • broadband
    broadband over 10 years
    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"; } }
  • Askolein
    Askolein over 10 years
    @surfen as if you forget it in ambiguous cases. I can break any argument by saying "but if you forget...".
  • Askolein
    Askolein over 10 years
    +1. I do not completly agree (method arguments?) but this is a very valid point.
  • Matt
    Matt over 10 years
    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.
  • djmj
    djmj about 10 years
    @Askolein You know save-action auto-formatting IDE functionality? There is no argument "but if you forget"
  • djmj
    djmj about 10 years
    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.
  • Lasse V. Karlsen
    Lasse V. Karlsen almost 10 years
    To chain construction to another constructor defined in the same type. public ClassName(...) : this(...).
  • Kira
    Kira over 9 years
    If I use 'this' keyword many times, will it reduce performance ?
  • Jakub Šturc
    Jakub Šturc over 9 years
    @Anand: Create a separate question please. Nevertheless please be more specific what usage of this keyword you have in mind.
  • aioobe
    aioobe over 9 years
    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
    aioobe over 9 years
    [...] 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.
  • Scott Wisniewski
    Scott Wisniewski over 9 years
    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.
  • aioobe
    aioobe over 9 years
    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.
  • phoog
    phoog about 9 years
    @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
    phoog about 9 years
    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.
  • wingerse
    wingerse over 8 years
    @Gunnar, there's an option to disable getting rid of redundant "this." in R#
  • Gunnar
    Gunnar about 8 years
    @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..." :)
  • Michael J.
    Michael J. over 7 years
    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.
  • m.rufca
    m.rufca about 7 years
    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.
  • wz366
    wz366 about 6 years
    In this case why don't just give different names to constructor's input variables?
  • Scott Adams
    Scott Adams about 5 years
    @juan, 10 years latter. You still think using "this" is good practice? :)
  • juan
    juan about 5 years
    @ScottAdams I still believe in consistency and clarity, yes
  • BornToCode
    BornToCode about 5 years
    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?
  • Jason Bunting
    Jason Bunting almost 5 years
    @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.
  • Jon
    Jon almost 5 years
    What a great comment @ScottWisniewski you've summed it up perfectly.