Friday, December 16, 2011

Extension method



You want to improve the syntax for calling common methods in your C# program, so that function names are shorter and easier to type. Extension methods provide a way to easily represent static methods as instance methods in the syntax of the C# language, which can be more intuitive and recallable for developers. Here we look at extension methods.

Example
Here is a custom extension method defined in a program written in the C# programming language. Generally, you will want to store your extension method class in a separate source file, such as "ExtensionMethods.cs" in your project. The file should store a static class with public static extension methods. In the rest of your source code, you can invoke these xtension methods in the same way as you can call instance methods.
Program that uses extension method on string [C#]

using System;
public static class ExtensionMethods
{    
    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 class Program
{    
    static void Main()
    {  
       // Use the string extension method on this value.  
       string value = "I'm proud to be an Indian.";
       value = value.UppercaseFirstLetter(); // Called like an instance method.                   
       Console.WriteLine(value);
    }
}
Output
I'm proud to be an Indian.

No comments: