14

Unless it is needed to differentiate between a variable and field with the same name, I never put this. in front of a field or any member access in C#. I see this as no different to m_ prefix that used to be common in C++, and think if you really need to specify that it's a member, your class is too big.

However, there are a number of people in my office that strongly disagree.

What is considered current best practises regarding this.?

EDIT: To clarify, I never use m_ and only use this. when absolutely necessary.

6
  • What is m_ supposed to mean? Apr 21, 2011 at 14:43
  • 2
    @Frustrated That the variable is a member of the class. Apr 21, 2011 at 14:45
  • Sorry, I'd made the assumption that no-one could possibly think I use Hungarian notation. I was trying to say I think this. is almost as bad as m_.
    – Andy Lowry
    Apr 21, 2011 at 15:18
  • 3
    Dude, just install and run StyleCop! This is also surely a dupe of a S.O. question.
    – Job
    Apr 21, 2011 at 16:39
  • 3
    Agreeing or disagreeing with your team is irregardless, You still need consistency in a team. Especially the larger the team gets otherwise it gets all willy nilly like the wild west and you know what people say about Cowboy coders. ;-)
    – Chris
    Apr 21, 2011 at 20:12

12 Answers 12

13

According to the Framework design guidelines, when referring to public or protected fields:

DO NOT use a prefix for field names.

For example, m_ is a prefix.

So, public exposure of a field lends itself to the usage of the this keyword as explained on MSDN

To qualify members hidden by similar names, for example: Copy

public Employee(string name, string alias) 
{
   this.name = name;
   this.alias = alias;
}

When referring to private fields, you can use the m_ if you want. But, for public fields I recommend following the best practices.

Personally, I don't like underscores in my variable names. I also try to be consistent. So, this.name = name; is a good rule of thumb to work in both public/private scenarios.

4
  • +1: This is what I was referring to in my answer, but your answer is much more descriptive. Apr 21, 2011 at 15:12
  • 1
    Agreed - I've seen several scenarios where you have a property, a member, and a local variable all with the same name. The property is Pascal (first letter capitalized) leaving you with two variables that are Camel cased (first letter lower). The only way to distinguish is with "this." (recommended) or a prefix (not recommended). I've used both and in practice the this keyword makes it easier to follow (IMO).
    – Mayo
    Apr 21, 2011 at 19:49
  • 1
    The funny thing with the framework advice is the CLR source is littered with the m_ prefix. I think '_' is a good prefix as you never worry about stackoverflow issues from assignment typos
    – Chris S
    Jul 13, 2011 at 12:55
  • 1
    @Chris S - In my experience Microsoft does well by documenting and maintaining an "evolutionary code process". They have used many practices that are now considered "bad practice". Most likely because they learned from their mistakes. This doesn't mean they went back and changed existing code as it is not always worth the effort. Just be sure to follow the latest guidelines in new - non-legacy application code. Jul 18, 2011 at 15:01
11

On our team, we have adopted the standard of using the this. or Me. object qualifier in larger classes to help junior developers more readily distinguish the exact/immediate scope of a variable just by looking at it.

Code-wise it is an entirely unnecessary affectation, but it doesn't block anything up since it generates the same exact MISL code in the end anyway. We've adopted it only because it addressed an immediate problem we discovered with some of the juniors. Beyond that, I don't see it as being helpful to include it.

6
  • Great point about the junior coders. Jul 13, 2011 at 8:39
  • 2
    Shouldn't your classes be smaller? Or is this a legacy issue?
    – Tjaart
    Aug 2, 2012 at 11:19
  • @Tjaart: Classes are as large or as small as they need to be. Even in a small class it can be easy to forget the scope of a variable just as it appears on the screen. Aug 2, 2012 at 11:50
  • 1
    Why do your juniors have problems @JoelEtherton? Python juniors have an opposite problem where they forget to add self. to access private variables. Don't the juniors just forget and mess up the convention?
    – Tjaart
    Aug 2, 2012 at 12:03
  • 1
    @Tjaart: Sometimes. They have problems because they're juniors, and sometimes they just don't pay attention or don't have a practiced eye yet. We used this technique more as a signpost than as a standard or convention. It's actually fallen into disuse here since this post now that all of our juniors have grown accustomed to the environment. I imagine if we hire new juniors (unlikely anytime soon) it may come back. Aug 2, 2012 at 12:25
10

StyleCop will enforce the use of this. So, if you regard that as best practice (which I do), then use of this. is best practice.

The style you adopt is up to you and your own coding standards, "best" is whatever you define it to be. Just be consistent. Using it inconsistently just leads to confusion.

My reasoning is that using this. calls out the fact that you are referencing instance properties, so, for example, it helps to highlight the fact that you are mutating them ( if you have this.x = ...), which is something you might want to know about. It also highlights the fact that any time you see this. your method can never be static. Using some convention like m_ will also do this, but it's a manual effort, if you make an m_ into a static, or refactor some method to pass in the value from outside the class then you have to remember to change the name, if you were using this then the compiler will force you to make the change.

Put simply using this is easier because if you get it wrong your code won't compile, if you use m_ it is a manual effort and you are not leveraging the tools.

3
  • 11
    And Resharper will suggest removing the "this.". Your mileage may vary.
    – Carra
    Jul 13, 2011 at 9:18
  • Eh? Resharper has never suggested that to me. Maybe it's because I have the StyleCop plugin? Aug 2, 2012 at 14:08
  • 1
    Correct, having StyleCop installed will turn off that option in R#.
    – Steve
    Aug 3, 2012 at 14:03
6

One of the nice things about using m_ is that as soon as you type the little m intellisense gives you a list of all of your private variables, personally I think that is a plus in it's favour; I would also go s_ for private statics and c_ for private constants for similar reasons. It's Hungarian notation, but in the sense it was meant because it adds useful meaning to variable name so that any other programmer can tell things about it from its name that may not be totally obvious.

I certainly don't agree with not having any way of distinguishing between member and non-member variables because they are different and when I read code where people don't do something to destinguish it is genuinely harder to read. Using this. just feels like more boiler plate than is necessary. But really it is personal taste, if you code one way for a while you end up thinking that is right and everything else is wrong. The only thing that really matters if the scheme is sane is that everyone in the team is consistent.

5
  • 4
    Or type this. and let intellisense help you.
    – Steve
    Apr 21, 2011 at 21:23
  • 1
    @Steve Haigh: you're missing the point, he's saying he gets to group all different types of member together, as the list is sorted alphabetically, all the m_ appear together, all the s_ together etc.
    – gbjbaanb
    Apr 22, 2011 at 0:03
  • 2
    using this. will give you everything in the class without needing to resort to out of date naming conventions. I understand the point of different letters, I just don't think they are necessary. If you have so many properties, constants etc in one class that you need this convention then you design is pretty much broken.
    – Steve
    Apr 22, 2011 at 11:52
  • 2
    @Steve Haigh: That is great in the theoretical world where everyone on the team is a great programmer and they all split their classes into small bitesized chunks and refactor well and have time to think about design etc... In my experience life does not quite qhite out like that. But I do agree in an ideal world you are probably right.
    – user23157
    Apr 22, 2011 at 12:10
  • @Steve: Typing m_ will give me a list of all member variables. Typing this. will give me a list of member variables and member functions.
    – Sean
    Jul 26, 2013 at 16:29
5

this is explicit. It's an optical sign you can't miss.

I almost always prefer explicit code over implicit code. That's why I use this frequently. I consider it a best practice.

5

I always use "this". The reasoning is based on two simple facts:

  • Reading code is more difficult than writing code.
  • You read code more often than you write code.

The use of "this" makes it quite explicit to anyone reading (i.e. not just the author, but may include the author in 6 months time after specifics of the implementation have been completely forgotten about) that yes, this is a class member we're talking about here. "m_" and the like is just a convention, and like any other convention it can be misused (or not used at all) - there is nothing to enforce "m_"/etc at either compile time or run-time. "this" is stronger: you can put "m_" on a local variable and the compiler won't complain; you can't do that with "this".

If anything I consider it regrettable that use of "this" was not made mandatory in language specs.

As a nice bonus, when debugging you can hover over (or add a watch for) the "this" and gain inspection of all other class members too - valuable information.

3

The this keyword is used particularly to distinguish 2 variables that exists, especially when doing you have a constructor or method of with a variable with the same name but can have same type.

Example:

public class Example {

    string reason;
    string cause;

    Example (string reason, string cause) {
        this.reason = reason;
        this.cause = cause;
    }

    //<Setter> if you want to explicitly write your onw
    public void setReason(stirng reason) {
        this.reason = reason;
    }
}

This (e.g. this.reason = reason) basically assigns the value from the parameters to the variables in the class. this basically takes the class reason from the parameter block.

2

I have also been wondering about that for some time. After doing some extensive coding in javascript, I caught myself using this. more often in my c# code (before that I used it almost exlusively in constructors or similar methods to avoid ambiguity). It makes the code a bit clearer for little additional effort, moreover you don't end up mutilating your class member names with prefixes and still can revert to using the members 'the short way' when context is clear or in particularly complex statements. I just add this., when I have a longer method, longer argument list or many local variables declared and I think the code could profit from some additional clarity, even if it's forced.

But I personally absolutely hate the m_ prefix style, not so much due to Hungarian, but because underscore is a pain to type ;) So I don't consider it an alternative. I'll admit it has it's strong points when it comes to intellisense, however you could again argue that if you can't remember the first few letters of a member variable, your class is to big.

2

I prever a single underscore prefix for class members. _someVar;

Why? You know at first glace that it's a member, not a stack variable. Just convenience during a quick glance. And it takes less clutter compared to the "this" keyword.

1

Using things like the this. prefix/keyword that are neither necessary nor change the outcome are always subjective. However, I think we can agree that most of us want to differentiate fields from local variables. Some use an underscore prefix (which I find ugly and a kind of Hungarian notation), others use the this. keyword. I am one of the latter. It is all just about readability and understandability. I never mind typing a little extra if it is clearer or more readable. I want to differentiate fields and variables in the blink of an eye.

I always define fields named similar to myField and parameter names and local variable names also similar to myField. No underscores, no prefixes. I use this everywhere I refer to a field. This way I can distinguish fields from local variables and arguments without any kind of prefix. Of course, in a case like this the this keyword is required:

public Person(string firstName)
{
    this.firstName = firstName;
}

My properties therefore look like this (yes, I always put the field with the property, and not somewhere unrelated at the top of my file):

private string firstName;
public string FirstName
{
    get { return this.firstName; }
}

It reads nicely: return this first name.

-2

EDIT: My answer is clearly not an answer. So here is an edit. The Microsoft coding guidelines state:

2.6 Naming

Do not use a prefix for member variables (, m, s_, etc.). If you want to distinguish > between local and member variables you should use “this.” in C# and “Me.” in VB.NET.

Can be found at: Link

So it would seem that at least from MS there is no clear guideline, although another answer does state that StyleCop makes it a guideline. There is no authority on these things, so I would suggest you make up your own mind, or in this case give in to your team. It's not such a big deal.

My original answer I personally agree with you, but maybe a reading comprehension test pitting the two methods against each other would be valuable. Otherwise these style things are just mudslinging.

My salvo to follow: My opinion is that people are unnecessarily complicating their code style, and if they need to indicate that something is a class level variable there might be some other serious structural issues in the code, like the age old recipe-method of putting private variables at the top of the class which force you to constantly scrolling up and down.

this strikes me as one of those "what this is" conventions versus the correct "what it does" naming conventions. Brevity should be favoured above being explicit. This is a lesson that is repeated often by dynamic languages. We don't need all the fluff!

3
  • 1
    -1. Instead of answering the question, you're just giving your opinion which doesn't reflect the best practices. Aug 2, 2012 at 13:37
  • So according to stylecop use of this. is best practice @MainMa . I totally disagree. I will edit the answer to note that.
    – Tjaart
    Aug 2, 2012 at 15:18
  • @MainMa is that better now? Many other answers give only an opinion, but are not downvoted. What are the best practices and where are they found?
    – Tjaart
    Aug 2, 2012 at 15:30
-3

this. can often lead to unwanted noise.

Here is my solution:

  • parameter_names_
  • local_variables
  • ANY_CONSTANT
  • _private_members
  • NonPrivateProperties
  • _NonPrivateProperty //Backer
  • privateProperty
  • _privateProperty //backer
3
  • 2
    This is very much in contradiction to common .Net style. camel and pascal casing all the way through. Your method is quite inconsistent. It's also quite an old style rule to capitilise constants, and its one that is not used in the general .Net community.
    – Tjaart
    Aug 2, 2012 at 11:25
  • I hope you put a comment at the top of each file explaining that scheme for to uninitiated... ;-)
    – jaybeeuu
    Jun 27, 2017 at 18:40
  • I don't understand how you think adding this. will create noise, but all of that jibberish doesn't Dec 28, 2019 at 17:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.