To use this…or not to use this

I”ll just start by wishing you all a great 2008!

Now, to what used to be a somewhat philosophical question: should you use this to reference a member of your class in your code? Ex: should you write this.CallInstanceMethod() ? Ok, in pre-C# 3.0, I”d say NO. With the current release, I”m saying maybe! Why? Simple: extensions methods. To call them, you must always pass a reference to the type, which means that if you”re calling an extension method from a class method (which is a scenario that should be very rare, but which is supported!) you must use the this qualifier or you”ll get a compiler error.

Advertisements

~ by Luis Abreu on January 2, 2008.

One Response to “To use this…or not to use this”

  1. I used to do it all the time, it”s even part of the code standard I developed for a company I worked for. One of the reasons for using “this” is that it immediately opens the intellisense dialog, another is that it”s easier to see what are member fields and what are method variables. However I”ve recently started to move away from this habit because it makes refactoring a method from being an instance method making it static a tad harder since all calls to the method has to be updated.

    However as I think of it now, I think that”s a silly argument and that the arguments for outweighs the arguments against, so my answer is simply. I use it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: