Thursday, August 5, 2010

What is extension Method?



Microsoft provides very powerful and useful feature in .Net 3.0 and above, one of them is Extension Method.

After declaring variable when we use that variable name and dot(“.”) we can find properties, these properties will be different for each data type.

If you declare int Count;

And write Count. You can see CompareTo, Equals, GetType...

These properties will be different for string or other datatype. We can create these properties and write customize code as per our requirement that called extension method.














Now, let’s create an extension method for int datatype.

Create and implement extension method.


To extend method, your class and property should be static. So create a new static class.

public static class ExtensionMethods
{
public static bool IsZeroOrNegative(this int value)
{
return (value <= 0) ? true: false ;
}
}


Here we check if value is less then or equals to 0 we return true other-wise false. This method will be extended with integer data type (we pass this int so it extend with int data type), now we can find extended property using Count.IsZeroOrNegative(); Here you can see, extension method is











==============================================
Hiren Raval |Senior Software Engineer

WebMingle Technology
Accelerated by knowledge. Driven by values.
www.webMingle.in

No comments:

Post a Comment