Search This Blog

Friday, April 6, 2012

Extension Methods in c#

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 is an example.

using System;
public static class ExtensionMethods
{
    public static string GetFirstThreeLatters(this string value)
    {

  if (value.Length > 0)
 {
        value=value.Substring(0,3);

}
 return value;
    }
}

class Program
{
    static void Main()
    {
 string value = "dot net perls";
 value = value.GetFirstThreeLatters(); // Called like an instance method.
 Console.WriteLine(value);
    }
}

OUTPUT:-

dot.


Description. In the first part of the program text, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code.
The extension method is called like an instance method, but is actually a static method. The instance pointer 'this' is received as a parameter. You must specify the 'this' keyword before the appropriate parameter you want the method to be called upon. In the method, you can refer to this parameter by its declared name.
This-keyword in parameter list. The only difference in the declaration between a regular static method and an extension method is the 'this' keyword in the parameter list. If you want the extension method to received other parameters as well, you can place those in the method signature's parameter list after the 'this' parameter.

No comments:

Post a Comment