Sunday 31 January 2016

What is extension methods and how to use them ?




 An extension method is a static method of a static class that can be invoked using the instance method syntax. Extension methods are used to add new behaviors to an existing type without altering. In extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by extension method.
Conceptually, extension methods provides as an implementation of the decorator structural pattern. At compile time an extension method call is translated into an ordinary static method call.


Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace DempApp
{

    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', ',' }).Length;
        }
    }

    class Program
    {
        public static void Main()
        {
            string s = "WCF WPF and DotNet trating program";

            //calling extension method
            int i = s.WordCount();

            Console.WriteLine(i);
            Console.ReadKey();
        }
    }
}


 Notes:-
  • An extension method is defined as static method but it is called like as instance method.
  • An extension method first parameter specifies the type of the extended object, and it is preceded by the "this" keyword.
  • An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
  • An extension method couldn't override the existing instance methods.
  • An extension method cannot be used with fields, properties or events.
  • The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.





No comments:

Post a Comment