Search...

Thursday, February 9, 2012

Extension Methods in C#

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.


Example.



using System;


namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
                ClassLibrary1.Class1 obj = new ClassLibrary1.Class1();
                obj.Show();
                obj.Print();
                Console.Read();
        }
    }


    public class Class1
    {
        public void Show()
        {
            Console.WriteLine("Hello World");
        }
    }


    public static class Class2
    {
        public static void Print(this ClassLibrary1.Class1 obj)
        {
            Console.WriteLine("I am Extension Method");
        }
    }
}





No comments: