Extension methods

Extension methods in C# allow us to add methods to an existing type without altering them or using inheritance. The extension methods are defined in the System.Linq.Enumerables namespace.

An extension method is always defined in a static class and as a static method. Along with that, it also uses the this keyword to qualify itself as an extension method. The following is a code example in which we have declared an extension method multiple on the int type. To identify the calling object as the first parameter being passed to the function, we have used the this keyword:

 

public static class IntExtensions
{
public static int MultiplyExtension(this int x, int y)
{
return x * y;
}
}
int z = 6;
Console.WriteLine(z.MultiplyExtension(5));
Console.ReadLine();

Once the preceding code is executed, we get the output of 30, which is the output when the calling object, 6, is multiplied by 5, which is declared in the extension method. In the next section, we will look at anonymous types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.134