Click here to Skip to main content
15,900,325 members
Articles / Programming Languages / C#

Basics concepts of Extension Methods

Rate me:
Please Sign up or sign in to vote.
4.74/5 (10 votes)
13 Aug 2012CPOL2 min read 34.6K   192   22   14
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

C#
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.

Image 1

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

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

See the sample code below:

C#
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.

C#
public interface MyInterface
{
    void DisplayClassName();
}

Extension Methods

C#
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.

C#
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

C#
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:

C#
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:

C#
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.

C#
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:

C#
public List<person> ListOfPerson;

The created extension method for filtering the ListOfperson object:

C#
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Artha is a Technical Lead in Windows Phone, WPF [MVVM, PRISM], ASP.NET [MVC 3.0 & 4.0], C#.NET, VB.NET and ASP.

Windows Phone

Microsoft Developer Network


Published Tools in Visual Studio Galleries


Published Source Codes in CodePlex


Microsoft Virtual Academy Profile


Published Articles in Code Project


Microsoft Certified Professional Developer (MCPD) Microsoft ASP.NET Developer 3.5 (070-564, 070-536, 070-562, 070 315)

Comments and Discussions

 
QuestionWell done. Pin
Septimus Hedgehog13-Mar-14 2:08
Septimus Hedgehog13-Mar-14 2:08 
AnswerRe: Well done. Pin
Arthanarieaswaran Shanmugaraj13-Mar-14 17:05
Arthanarieaswaran Shanmugaraj13-Mar-14 17:05 
GeneralMy vote of 5 Pin
Abdul Quader Mamun15-Aug-12 1:26
Abdul Quader Mamun15-Aug-12 1:26 
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun15-Aug-12 1:26
Abdul Quader Mamun15-Aug-12 1:26 
GeneralRe: My vote of 5 Pin
Arthanarieaswaran Shanmugaraj15-Aug-12 17:11
Arthanarieaswaran Shanmugaraj15-Aug-12 17:11 
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun15-Aug-12 17:45
Abdul Quader Mamun15-Aug-12 17:45 
GeneralMy vote of 5 Pin
vrmgopi14-Aug-12 23:10
vrmgopi14-Aug-12 23:10 
GeneralRe: My vote of 5 Pin
Arthanarieaswaran Shanmugaraj15-Aug-12 17:11
Arthanarieaswaran Shanmugaraj15-Aug-12 17:11 
GeneralMy vote of 5 Pin
manticorebp14-Aug-12 5:07
manticorebp14-Aug-12 5:07 
GeneralRe: My vote of 5 Pin
Arthanarieaswaran Shanmugaraj15-Aug-12 17:08
Arthanarieaswaran Shanmugaraj15-Aug-12 17:08 
SuggestionOverloading resolution? Pin
Andreas Gieriet9-Aug-12 13:27
professionalAndreas Gieriet9-Aug-12 13:27 
This tip is a nice starting point - my 4 for it.
What you should consider when implementing extension methods is, how they behave in conjunction with overloading.

Can you elaborate a bit on this - maybe resulting in an advise on how to handle/avoid overloading issues.

E.g. questions like:

  • What if an extension method matches better than any of the this class members?
  • What if the this is of a chained and mixed interface implementation, e.g. like in LINQ:
    C#
    public interface IEnumerable<out T> :                             IEnumerable { ... }
    public interface IQueryable<out T>  : IEnumerable<T>, IQueryable, IEnumerable { ... }
    ...
    public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source) { ... }
    ...
    public static TSource FirstOrDefault<TSource>(this IQueryable<TSource> source) { ... }
    ...

    It will not work as expected if the implementations of these interfaces are not done appropriately. I.e. it seems that the sequence in which the classes define their interfaces is relevant... (class C: IA, IB {...} is not equal to class C: IB, IA {...} for what concerns overloading).

Extension methods are a powerful concept as the various LINQ implementaitons and their generic usage of Enumerable and Queriable classes show. If you define your own extension methods that build on similar interfaces and class trees, be careful to know exactly what you do.

This issue holds for overloading in general - this is not specific to extension methods.

Cheers
Andi

modified 10-Aug-12 2:08am.

GeneralRe: Overloading resolution? Pin
Arthanarieaswaran Shanmugaraj9-Aug-12 16:22
Arthanarieaswaran Shanmugaraj9-Aug-12 16:22 
GeneralMy vote of 5 Pin
Christian Amado9-Aug-12 10:49
professionalChristian Amado9-Aug-12 10:49 
GeneralRe: My vote of 5 Pin
Arthanarieaswaran Shanmugaraj9-Aug-12 16:10
Arthanarieaswaran Shanmugaraj9-Aug-12 16:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.