Thursday, November 19, 2015

What is Extension methods in C#?

What is extension method?
Extension method enable us to add a method in types without modifying , recompiling or deriving existing types.
Extension method is static method but called as instance method of types. 
                      Extension method is declared as static in static class where 'this' modifier is first parameter.
The type of first parameter is type that is extended.   
                                            
Extension methods has following features:
1. Sealed class can be extended using extension method.
2. Extension method should not extended method with same signature from type.
3. Extension method cannot be used to override the existing method.
4. Concept of extension method cannot be applied to fields, properties and event.

Ex: I am going to extend the assembly which i have created.


Create class library with name ClassLibrary1 using Visual studio. Add following code to library.

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

namespace ClassLibrary1
{
    public class Class1
    {
        public string Disp()
        {
            return "yes";
        }
    }
}

Now create a console application ConsoleApplication2.
Now add following code to console application.

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            ClassLibrary1.Class1 c = new ClassLibrary2.Class1();
            c.Show();
            c.Disp();
            
            Console.ReadLine();
        }
    }


    public static class sub
    {

        public static void Show(this ClassLibrary2.Class1 cls)
        {

            Console.WriteLine("show");
        }
    }
}

Method Show is available in Class1 of ClassLibrary2.

No comments:

Post a Comment

Write a program to reverse a string? using System; namespace ConsoleApp1 {     class Program     {         static void Main(string[] args)  ...