Search This Blog

Sunday, July 7, 2019

Extension Method C#

Extension method  give feature to   add  method to existing  types without creating a new derived type,recompiling or other wise modifying the original type
 Feature
1. It is a static method

2. It must be located in the static class

3. It  uses "this" Keyword as the first parameter

Program to show how to use extension methods


Create a project Class Library as:

using System;  
using System.Text;  
  
namespace ClassLibExtMethod  
{  
    public class Class1  
    {  
        public string Display()  
        {  
            return ("I m in Display");  
        }  
  
        public string Print()  
        {  
            return ("I m in Print");  
        }  
    }  


using System;  
using System.Text;  
using ClassLibExtMethod;   //pass reference
  
namespace ExtensionMethod1  
{  
    public static class XX  
    {  
         public static void NewMethod(this Class1 ob)  
        {  
            Console.WriteLine("Hello I m extended method");  
        }  
    }  
  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            Class1 ob = new Class1();  
            ob.Display();  
            ob.Print();  
            ob.NewMethod();  
            Console.ReadKey();  
        }  
    }  



No comments :