Wednesday 24 April 2013

Extension Methods


In .NET, extension methods provide a mechanism by which you can add functionality to a type without
modifying it to avoid the risk of breaking code in existing applications. You can also add additional
methods in the interface without altering the existing class libraries.
So the extension method allows you to extend the existing compiled types to have a new functionality
without needing to directly update the type. It is quite helpful when you need to inject new functionality
into types where you do not have an existing code base. It can also be useful when you need a class to
support a set of members, but it cannot modify the original type declaration. Using the extension method,
you can add functionality to compiled types while providing the illusion that these methods were there all
along.
To extend a type’s functionality using the extension method technique provided by the C#, you need
to do the following:
• Make a static class.
• Add a static method in this static class with the appropriate functionality. In the
parameter list of this new method, add an extra parameter this along with the type
name for which this method will extend the functionality. For example,
GetLastCharacter method in below extends functionality for the string type.

an extension method is defined for the string type. This extension method is used to
determine the last character of a word whose type is string.

 An Example of the Extension Method :

using System;
namespace ExtensionMethod
{
class Program
{
static void Main(string[] args)
{
string data = "abcd";
Console.WriteLine("{0}", data.GetLastCharacter()); /* Calls extension defined for
the string type. */
}
}
public static class ExtensionMethods /* A Static class defined */
{
public static string GetLastCharacter(this string data)
/* A static method with the parameter
* this along with the type name string */
{
if (data == null || data == string.Empty)
return string.Empty;
return data[data.Length - 1].ToString();
}
public static Int32 GetNum(this Int32 dd)
{
return dd;
}
}
}

The program will produce the following output:
d


The GetLastCharacter extension method determines the last character from the input data if the data
are not null or do not contain an empty value. In above code, a static class ExtensionMethods is
defined and a static method GetLastCharacter is added. The first parameter contains the this keyword
along with a parameter of the type that is going to be extended, in this case it is string.
When you define any extension method for a type, it shows Visual Studio’s IntelliSense along with the
standard methods of that type.

Cheers,
Mani Kumar Yegateeli

No comments:

Post a Comment