Extension Methods in C#


Introduction

Extension methods are a convenient way to add methods to classes that you don’t own and so can’t modify directly.

Look at the program given below:

using System;
using System.Collections.Generic;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //create the object of the class
            Person p = new Person() { Name = "Abhimanyu", Age = 22 };
 
            //see the result
            Console.WriteLine(p.Name + ", " + p.Age);
            Console.ReadKey();
        }
    }
 
    //class
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
 
In the above program, I have a ‘Person’ class having two properties ‘Name’ and ‘Age’ and the same I have created an object of the ‘Person’ class in main method by the name ‘p’ and then assigning the property value.

Assume I want to extend the ‘Person’ class (reason may be anything like don’t own class etc.) then what we need to do is to extend the ‘Person’ class by using a static directive (class or method). Look at the program snap below.

//extension method

static class ExtensionMethod
{
    public static string Introduce(this Person person)
    {
        return string.Format("Hello {0} ", person.Name);
    }
}
 
In above code the key points are, class or method should static type and in ‘Introduce’ method parameters we need to write the name of class (as ‘Person’) which we are extending and its new name (as ‘person’).

Find the complete program here.

using System;
using System.Collections.Generic;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //create the object of the class
            Person p = new Person() { Name = "Abhimanyu", Age = 22 };
 
            //see the result
            Console.WriteLine(p.Introduce());
            Console.ReadKey();
        }
    }
 
    //class
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
 
        /*
        public string Speak()
        {
            return string.Format("Hello {0} ", Name);
        }
        */
    }
 
    //extension method
    static class ExtensionMethod
    {
        public static string Introduce(this Person person)
        {
            return string.Format("Hello {0} ", person.Name);
        }
    }
}
 
I hope you will enjoy learning it. Thanks



Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System