Saturday, 22 March 2014

what is extension method in c# ?

Extension method enable you to “add” to existing type without creating new derived type recompiling or otherwise modify the original type. Extension method is a special kind of static method, but they are called as if they were instance method on the extension type.
@Code Snippet
Method declaration to count the number of word in string.
   public static class Myextension
        public static int WordCount(this string str)
            return str.Split(new char[]{' ','.','?'},StringSplitOptions.RemoveEmptyEntries).Length;
Call Extension method
static void Main(string[] args)
            string strValue = "this is my string";
            Console.WriteLine("String = " + strValue + " \nTotal Word : " + strValue.WordCount());
OutPut Value
Differences between Static Method and Extension Method?
1.       Extension method is having this keyword before the first argument.
2.       Extension method is defined only in static class.
3.       Extensions method call in instance value.

No comments:

Post a Comment