Advanced C# – Extension Methods

The extension methods came up with the version 3.0 of the .net framework. Basically it gives us the possibility to use the syntax to call a method (object.method()) defined as static method. The compiler gives us the illusion that we are invoking a method that belongs to our object but in fact we are only invoking a static method defined in another place.

Lets take a look to the following example

public static class Extensions
{
public static string Left(this string s, int num)
{
if (string.IsNullOrEmpty(s)) return string.Empty;
if (num <= 0) return string.Empty;
if (num <= s.Length) return s.Substring(0, num);
return s;
}
}

We defined a static class Extensions that has a static method Left until this point there is nothing new just a normal static class. Anyway you can realize that as first parameter we use the operator this which is the owner to make this normal static method into a Extension Method and allow us to make this:

var text = "This is my string text";
var text2 = text.Left(17);

As you can see we can invoke the method defined in the static class as it is part of the object (in my case text is a string object). What happen internally?  The compiler invoke the static method in the normal way Extension.Left(text, 17) using as first parameter the object which has invoked the extension method.

This is how to define an extension method so lets now review a few definitions:

  • The extension methods are not part of the class which are extending. It means that an extension method can’t access to the protected method of the class that invokes it.
  • They must be defined in a static class therefore all of them must be static.
  • They can be invoked in a null reference and it doesn’t throw an exception.
  • The extended class can be a sealed class.
  • The extended class can be replaced by an interface.
  • The extended method are “normal” method for this reason you can invoke it as I did before using the normal way.
  • The extended class can be defined as Generics.

This is a good tool to extend class behavior without doing a modification on the extended class. Later on I will write another post to show how we can use this extension method to create an HTML Helper.

Advertisements

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