Sunday, 7 January 2018

What is extension method in c#

Extension method is that used to extend the existing class without modifying the structure of the class.

It can be achieved by static class with static member and using this keyword.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExtensionMethod
{
    public class ExtendClass
    {
        public void Display()
        {
            Console.WriteLine("Hi this is display method.");
        }
    }

    static class Program
    {
        public static void  NewDisplay(this ExtendClass cls)
        {
            Console.WriteLine("Hi this is new display method.");
        }

        static void Main(string[] args)
        {
            ExtendClass cls = new ExtendClass();
            cls.Display();
            cls.NewDisplay();
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment