Click here to Skip to main content
Click here to Skip to main content

Basics concepts of Extension Methods

By , 13 Aug 2012
Rate this:
Please Sign up or sign in to vote.

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

About the Author

Arthanarieaswaran
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. PinmemberSeptimus Hedgehog13-Mar-14 2:08 
AnswerRe: Well done. PinpremiumArthanarieaswaran13-Mar-14 17:05 
GeneralMy vote of 5 PinmemberAbdul Quader Mamun15-Aug-12 1:26 
GeneralRe: My vote of 5 PinmemberAbdul Quader Mamun15-Aug-12 1:26 
GeneralRe: My vote of 5 PinmemberArthanarieaswaran15-Aug-12 17:11 
GeneralRe: My vote of 5 PinmemberAbdul Quader Mamun15-Aug-12 17:45 
GeneralMy vote of 5 Pinmembervrmgopi14-Aug-12 23:10 
GeneralRe: My vote of 5 PinmemberArthanarieaswaran15-Aug-12 17:11 
GeneralMy vote of 5 Pinmembermanticorebp14-Aug-12 5:07 
GeneralRe: My vote of 5 PinmemberArthanarieaswaran15-Aug-12 17:08 
SuggestionOverloading resolution? [modified] PinmemberAndreas Gieriet9-Aug-12 13:27 
GeneralRe: Overloading resolution? PinmemberArthanarieaswaran9-Aug-12 16:22 
GeneralMy vote of 5 PinmemberChristian Amado9-Aug-12 10:49 
GeneralRe: My vote of 5 PinmemberArthanarieaswaran9-Aug-12 16:10 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140421.2 | Last Updated 13 Aug 2012
Article Copyright 2012 by Arthanarieaswaran
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid