15

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.

Andy Lowry
  • 2,422

12 Answers12

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.

P.Brian.Mackey
  • 11,121
  • 8
  • 53
  • 88
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.

Joel Etherton
  • 11,684
  • 7
  • 47
  • 55
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.

Steve
  • 5,264
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

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.

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.

Falcon
  • 19,388
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.

scrwtp
  • 4,542
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.

jojo
  • 598
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!

Glorfindel
  • 3,167
Tjaart
  • 1,891
-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
Mark
  • 336