Tuesday, December 9, 2014

Extension Methods


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.

An Extension Method has simplified calling syntax. It represents static methods as instance methods. An extension method uses the this-keyword in its parameter list. It must be located in a static class.




  public static class ExtensionMethods
    {
        public static string UppercaseFirstLetter(this string value)
        {
 //public static string UppercaseFirstLetter( string value,this string value1)///Invalid -'this' which is not on the first parameter
        //public static string UppercaseFirstLetter(this string value,string value1)///valid
        public static string UppercaseFirstLetter(this string value)
        {
            // Uppercase the first letter in the string this extension is called on.
            if (value.Length > 0)
            {
                char[] array = value.ToCharArray();
                array[0] = char.ToUpper(array[0]);
                return new string(array);
            }
            return value;
        }

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

static void Main(string[] args)
 {
   // Use the string extension method on this value.
   string value = "hello extension methods";
   value = value.UppercaseFirstLetter(); /// Called like an instance method.
   int i = value.WordCount();/// Called like an instance method.
   Console.WriteLine(value);
   Console.WriteLine(i);
 }
 


Output

Hello extension methods
3

Refer
http://msdn.microsoft.com/en-IN/library/bb383977.aspx
http://www.dotnetperls.com/extension 

No comments:

Post a Comment