Friday, March 25, 2011

Required use of the "this" keyword in C#

When it comes to member variables I prefer an underscore and I'm not going to apologize to the Hungarian notation police! It fits my eye and I like the way it looks in my code. However, the team that I currently work in has different ideas and the standard is to use "this" everywhere...

Now I'm okay with this obviously. Whatever the team chooses is fine by me and once everybody agrees to use the same standards then that is the important thing.

It is interesting that Resharper highlights the redundancy of it by default Qualifier 'this.' is redundant and Stylecop warns you to include it! I find it litters up your code pretty quickly with noise.

Anyhow, I really wanted to find out the uses of the keyword that are not related to style. So here is a list of required uses (i.e. you absolutely have to use it and it is not just a style choice)
  1. To qualify members hidden by the same 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.
In these cases the 'this' keyword has a clear purpose, in all other cases it is a style issue. Of course the key thing here is that it really doesn't matter. The compiled code has the IL equivalent of this inserted anyway whether or not you include it in your code and there are definitely more important things to worry about!

Some interesting links on the topic









No comments:

Post a Comment