Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Basics concepts of Extension Methods

0.00/5 (No votes)
13 Aug 2012 2  
The basic concepts and implementation of Extension Methods.

About This

This article helps to understand Extension Methods in C#. I have explained Extension Methods with a simple console application.

Introduction

Extension Methods help add some additional methods to existing types (String, Integer, etc.), they are static methods. In this article, I have explained extension methods for existing types, classes, and Lambda/LINQ queries. For better understanding of this article, please download and run the code once.

Creating an Extension Method

An extension class and method should be static and the first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.

Extension Method for Existing Types

Below class extending the string type

public static class MyExtention
{
    public static string HelloString(this string vstr)
    {
        return string.Format("Hello {0}!", vstr);
    }
}

After running the above code and creating a string type, IntelliSense will show the custom method HelloString.

The HelloString extension method can be called in the two different ways:

  • name.HelloString();
  • MyExtention.HelloString(name));

See the sample code below:

public class StringExtensionDemo
{
    public void Run()
    {
        Console.WriteLine("Enter Name: ");
        string name = Console.ReadLine();

        Console.WriteLine("Console.WriteLine(name);");
        Console.WriteLine(name);

        Console.WriteLine("Console.WriteLine(name.HelloString());");
        Console.WriteLine(name.HelloString());

        Console.WriteLine("Console.WriteLine(MyExtention.HelloString(name));");
        Console.WriteLine(MyExtention.HelloString(name));
    }
}

Extension Method for Classes

I have created a simple interface that contains a method and added some extension methods for extending the interface.

See the code sample below.

public interface MyInterface
{
    void DisplayClassName();
}

Extension Methods

public static partial class MyExtention
{
    public static string HelloString(this string vstr)
    {
        return string.Format("Hello {0}!", vstr);
    }

    public static string HelloClass(this MyInterface vInterface, string vstr)
    {
        return string.Format("Hello Extension, '{0}' is a string!", vstr);
    }

    public static string HelloClass(this MyInterface vInterface, int vint)
    {
        return string.Format("Hello Extension, '{0}' is an integer!", vint);
    }

    public static string HelloClass(this MyInterface vInterface, object vint)
    {
        return string.Format("Hello Extension, '{0}' is an object!", vint);
    }
}

Construct a class named ClassB inherited from MyInterface.

public class MyClassB : MyInterface
{
    public void DisplayClassName()
    {
        Console.WriteLine("This is MyClassB");
    }
}

public class MyClassBDemo
{
    public void Run()
    {
        MyClassB first = new MyClassB();
        first.DisplayClassName();
        Console.WriteLine(first.HelloClass("MyClassB"));
        Console.WriteLine(first.HelloClass("MyClassB".Length));
    }
}

In the above code MyClassB has only the DisplayClassName method, but an instance of that class can call the HellClass method and also based on the argument passed, the corresponding extension method will be called.

If argument is string type, then

public static string HelloClass(this MyInterface vInterface, string vstr)
{
    return string.Format("Hello Extension, '{0}' is a string!", vstr);
}

If argument is int type, then:

public static string HelloClass(this MyInterface vInterface, int vint)
{
    return string.Format("Hello Extension, '{0}' is an integer!", vint);
}

If arguments are other than string and int, then:

public static string HelloClass(this MyInterface vInterface, object vint)
{
    return string.Format("Hello Extension, '{0}' is an object!", vint);
}

The complier looks into whether the instance of the class MyClassB has the HelloClass method, if available then the compiler will run that method, otherwise run the extension method.

Please see the attached zip project for detailed code and I have added inline comments.

Extension Methods in Lambda

Extension methods are used in Lambda/LINQ query operations. I have created an object class Person.

public class Person
{
    public int ID { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }

    public string Gender { get; set; }
}

And created a variable to hold the list of person objects:

public List<person> ListOfPerson;

The created extension method for filtering the ListOfperson object:

public static List<person> OrderByName(this List<person> persons)
{
    return persons.OrderBy(x => x.Name).ToList<person>();
}

public static List<person> Under18(this List<person> persons)
{
    return persons.Where(x => x.Age < 18).ToList<person>();
}

public static List<person> Plus18(this List<person> persons)
{
    return persons.Where(x => x.Age >= 18).ToList<person>();
}

public static List<person> Male(this List<person> persons)
{
    return persons.Where(x => x.Gender == "M").ToList<person>();
}

public static List<person> Female(this List<person> persons)
{
    return persons.Where(x => x.Gender == "F").ToList<person>();
}

Using the above extension method, I can easily do sorting and filtering of the ListOfPerson object.

ListOfPerson.OrderByName();
ListOfPerson.Under18().OrderByName();
ListOfPerson.Under18().Female().OrderByName();

Please see the attached code for details and run the code and it will give more information on the extension methods.

Conclusion

I hope this article helps you to understand the basic concepts of extension methods. Please let me know your comments and questions on this article.

References

  1. http://msdn.microsoft.com/en-us/library/bb383977.aspx
  2. http://msdn.microsoft.com/en-us/library/bb311042

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here