Saturday, January 5, 2013

What is the use of Extension Method in C#?


Extension Method

Extension method is generally used to extend the class functionality without changing the existing class contents.

Example

Let’s take an example of string class and try to add one new method (CountChar) into the existing string class without changing the string class content.

    public static class MethodExtension
    {
        public static int CountChar(this string x)
        {
            return x.Length;
        }
    }
    static void Main()
    {
        string str = "Anjali";
        Console.WriteLine(str.CountChar());
     }



No comments:

Post a Comment