Extension Methods in C#

Posted by dariosantarelli on August 6, 2007

An interesting feature of the .NET Framework 3.5 is that any set of methods available on an instance of a particular type is open to extension. Effectively, adding new methods to existing types is now possible.By using extension methods, we can declare static methods that can be invoked using the instance method syntax. In order to declare an extension method we must specify the keyword this as the first parameter of the static method.
Let’s show an example:

1. We have a Customer class, which needs of another method “Logout”:
2. Instead of using an inherited class, we add the “Logout” method to our Customer class by declaring a static method which can be invoked directly in any Customer class instance.

3. Finally, in our code we can invoke our “Logout” extension method in this way:

When extension methods are consumed, the argument that was declared with the keyword this is not passed, while all other arguments will be passed and seen by intellisense.  So, the first argument in the declaration (keyword this) allows the compiler to determine the class instances on which the extension method is called.
Remember that extension methods, though declared as static, can be called only on instances values!!!


4 Responses to “Extension Methods in C#”

  1. mullr said

    This is really interesting… how widely applicable is the technique? Does it work with properties? More importantly, can additional data be attached to the object in question?

    C# seems to be getting more dynamic all the time, a direction that greatly pleases me.

    – Russell

  2. Hi Russell
    Well, this feature allows the business objects development more flexible, because you can add functionality to existing types even if you don’t have the source code!!! However, I think this technique is not so widely applicable and partially useful because it affects just instances values.

    This feature is not applicable to object properties (maybe in the future…:)).

    What do you mean by “attached”? Anyway the only addition you can apply to your objects is methods.

    This direction pleases me too ;)… moreover, extension methods don’t change the original object type, so other libraries working with the same type won’t be affected.

  3. My friend on Facebook shared this link and I’m not dissapointed that I came here.

  4. Usettecob said

    Absolutely keen trap have here! My friend actualy sent me a fasten together! Friendly fate!

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: