Extension Methods

They are static methods that can be invoked like an instance method. Static methods can be declared only in Static classes. Let’s see how extension methods are declared.
public static void ExportToExcel(this DataSet ds)
{
//do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
public static class Extensions
{
public static void ExportToExcel(this DataSet ds)
{
//do something…
}
}
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel();

Leave a comment

Filed under C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s