Monday, July 19, 2010

Usage of C# 'this' keyword

Use of the this keyword, is very much a style thing.  However there is a great deal of logic behind the recommendation to use it.  

Most developers have some kind of consistent style they follow, and consistency is a good thing.  In my opinion following historic 'traditions' need to be occasionally challenged to ensure the science and logic behind the original recommendation is still valid.  I'm sure everyone would agree that technology and methodology in the software industry is extremely fast moving. So keeping all things current make sense.

The overall goal in any style convention is to consistently add value to code by narrowing the number of ways a piece of code can be interpreted. However the code should always be as readable as possible. The more readable it is, the less chance for bugs.

Here's an example of how the 'this' keyword can make code more readable, indicate scope, and indicate member or static access:

// Its clear m_Something is a field, 
// but what is Something2?
// Something2 could be property, or a 
// method reference, or a static member.
// Its clear something is a field 
//- "this" means instance; lowercase 
// first letter 's' means private field.
// Something2 is clearly a static member 
// or constant by the Class name prefix 
// and the captial letter also indicates
// constant or readonly static.
m_Something = Something2;this.something = ClearerUsage.Something2;
// What is Something.Bar? Static class 
// with a static property or member property
// access?

// Something4 same questions as above.
// Something can only be a member property, it 
// cannot be a field due to casing of 
// the 'S'. And Bar is a member access of 
// Something. It cannot be a static of 
// Something otherwise it would be Foo.Bar 
// (Foo being the type of Something).
// Something4 same as above Something2,3,5.
Something.Bar = Something4;this.Something.Bar = ClearerUsage.Something4;
// Could be a instance or static method.// This can only be a member method.
Logically 'this' definitely adds value and is much clear than using Hungarian style prefixes. This also indicates scope as well as static versus member access. I know the code will compile without it, but increasing readability of the code and reducing ambiguity DOES reduce bugs. Using a built in language construct does make more sense than inventing a prefixing or suffixing scheme.

No comments:

Post a Comment