Android Application Architecture

Android Application Architecture

Advertisement

.net 3.0 – Extension Methods

Extension methods are simple but very powerful feature of .net 3.0 framework.

Extension methods can be used as their name suggests to extend any built-in type in .net.

To explain the concept we will use an example of traditional way of adding a function to find if an int is even.

And then move on to the new concept of Extension method.

Traditionally, if you wanted to define a function to find if a number is even, then you would a utility class and then add the function as a Static function in that class.

class Utility

{

public static bool isOdd(int value)

{

return (value %2 !=0);

}

}

The usage would be as follows:

private static void CheckEven(int num)

{

if (Utility.isOdd(num))

Console.WriteLine(“{0} is Odd “,num);

else

Console.WriteLine(“{0} is Even “, num);

Console.ReadLine();

}

And now moving on to the new feature of extension methods

public static class Extensions

{

public static bool IsEven(this int value)

{

return (value % 2 == 0);

}

}

The usage is simple

extension method

As you can clearly see that the extended method IsEven appears automatically as a method of type int and is shown in the VS2008 intellisense.

We have defined the same CheckEven() function this time with an Extension method

private static void CheckEven(int num)

{

if (num.IsEven())

Console.WriteLine(“{0} is Even “,num);

else

Console.WriteLine(“{0} is Odd “, num);

Console.ReadLine();

}

We will go through the extension method definition once again to understand how to define an Extension method:

public static class Extensions

{

public static bool IsEven(this int value)

{

return (value % 2 == 0);

}

}

There are a few simple rules which re used to define an Extension method, these are as follows:

  1. The class in which the Extension method is to be defined should be static.
  2. The extension function itself should be public and static.
  3. The type which has to be extended should be the first parameter and also should be preceded by the this keyword.

As you can see that the Extension methods are very powerful and easy to use and if used properly with proper documentation can improve the reusability of a code. And which will help the developer community in the long run.