Extension Methods in C# 3.0

The latest incarnations of the .NET languages include a slew of new features, and extension methods in C# is just one of them. Extension methods allow you to extend a class without subclassing it. You might be asking yourself "Why would I want to do that? Why not just subclass?" Well, what if the class you want to subclass is sealed, preventing you from subclassing it? Extension methods allow you to extend even sealed classes.

Let's say you have a class called Dog. Dog has all of the properties and methods of a real dog, including a Bark() method. Because of the strained relationship in the neighborhood between cats and dogs, you want your dogs to be able to meow to help further the cause of cat/dog co-existence. There's just one problem: the Dog class is sealed and can't be subclassed. The answer lies with extension methods.

First, create a static class. Extension methods must be part of a static class. Second, create a static member of the static class. The first parameter of the method should be of the type you wish to extend, and should be preceeded with the "this" modifier. To give our Dog class the ability to bark, we could write the following:

public static class DogExtensionMethods
{
   public static void Meow(this Dog dog)
   {
      Console.WriteLine("Meow!");
   }
}

That's all there is to it. Of course, this is a very simple (and, admittedly, ridiculous) example, but you get the point. Another cool thing is that extension methods show up in Intellisense. Check it out:


Notice that the icon for the extension method is a little different than that used for regular methods, and that Intellisense differentiates the method as an extension method in the tooltip text. Neat!

Comments

Popular posts from this blog

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception