Extension Method in C#


Extension method is the one of the cool features came in C# 3.0. As the name suggest, it extends the functionality of method in very simple way.

For example, we are going to use some dll method and we don’t have access to inherit or override the class. But our requirement is there to extend the method with some extra functionality. Then extension method will very handy to use in this scenario.

Let’s see one extremely simple example

Extension_Method

Complete code in C#

using System.Collections.Generic;
 
namespace ExtensionMethod
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            EmpElite objee = new EmpElite();
            objee.AllEliteEmps(); //This will contains Ram, Mohan,Hari
            objee.NewEliteEmps(); //This will contains John,James,Suresh
        }
    }
 
    public class EmpElite
    {
        public List<string> AllEliteEmps()
        {
            return new List<string> { "Ram", "Mohan", "Hari" };
        }
    }
 
    public static class ExtendedEmpElite
    {
        public static List<string> NewEliteEmps(this EmpElite elite)
        {
            return new List<string>() { "John", "James", "Suresh" };
        }
    }
}

Note:
In the above example, we saw that there is one EmpElite Class with AllEliteEmps method, Which contains the list of elite Emps. We have extended the AllEliteEmps method with NewEliteEmps using static Keyword and this Keyword. We have also passed the Class name and instance name which one we are going to extend.

Now whenever we will call this method i.e. ExtendedEmpElite then we will get the expected output.

Point to remember:
• An extension method must be defined in a top-level static class.
• An extension method with the same name and signature as an instance method will not be called.
• Extension methods cannot be used to override existing methods.
• The concept of extension methods cannot be applied to fields, properties or events.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: