Simple Example of Extension Methods in C#

Let’s say you have a C# class named Person that has a property and a method.

Here’s the Person class:

    1 public class Person

    2 {

    3     public string Name { get; set; }

    4     public string Speak()

    5     {

    6         return (string.Format(“The time is {0}.”, DateTime.Now.TimeOfDay.ToString());

    7     }

    8 }

Now let’s say that, for whatever the reason, you are not allowed to make any changes to the Person class (For example, you have been given the class in the form of a .dll assembly). As you are writing your code and consuming the Person class, you run into an issue such that you need for the Person class to return the favorite number of the Person instance. In other words, as the consumer of  the Person class, you wish the class was designed like this:

    1 public class Person

    2 {

    3     public string Name { get; set; }


    5     public string Speak()

    6     {

    7         return (string.Format(“The time is {0}.”, DateTime.Now.TimeOfDay.ToString());

    8     }


   10     public int FavoriteNumber()

   11     {

   12         return (new Random().Next());

   13     }

   14 }

Notice the added method named FavoriteNumber().

Well, since you are not allowed to modify the Person class, what do you do?

This is where Extension Methods can be a great help.
MSDN defines Extension Methods as:

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Using the Extension Methods model, we can implement a method that “feels” like it is a member of the Person class without making any change to the Person class. Here’s how we can do that…

  1. We are not allowed to make any changes to the Person class, so we’ll leave that alone
  2. We’ll create a new class and name it ExtensionsLibrary

        1 public static class ExtensionsLibrary

        2 {

        3     public static int FavoriteNumber(this Person person)

        4     {

        5         // Return a random number for our example

        6         return (new Random().Next());

        7     }

        8 }

    The ExtensionsLibrary is a class that we can add extension methods to. The class must be a static class. If we don’t specify it as a static class we will get the exception:
    Extension method must be defined in a non-generic static class.
    In this example we have only one extension method that we named “FavoriteNumber”. The extension method must also be static. The first parameter (Person person) which type the method operates on – this is where the magic occurs. The first parameter is how we tell the compiler that the FavoriteNumber is extending the Person class. Lastly, we must precede the first parameter with the “this” modifier.

  3. Now this is how you can use the Person class and call the extension method

        1 class Program

        2 {

        3     static void Main(string[] args)

        4     {

        5         // Create a Person instance

        6         Person p = new Person { Name = “Frank” };


        8         // Call the Extension Method to get the Person’s favorite number

        9         int favNumber = p.FavoriteNumber();


       11         Console.WriteLine(“{0} says {1}\r\n{0}’s favorite number is {2}.”, p.Name, p.Speak(), favNumber);

       12         Console.ReadLine();

       13     }

       14 }

Here’s a video that demonstrates how to create extension methods for strong types and generic types.


Leave a Reply

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

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