Extension Method
The extension method feature allowing to write methods associated with classes other than the class in which they are declared. For example I have a class like following:
When you want to add method to the class, we can use extension method. With following requirements:
Lets add a method to calculate average to
And here's our
The output will be:
class MyData { private double D1; // Fields private double D2; private double D3; public MyData(double d1, double d2, double d3) // Constructor { D1 = d1; D2 = d2; D3 = d3; } public double Sum() // Method Sum { return D1 + D2 + D3; } }
When you want to add method to the class, we can use extension method. With following requirements:
- The class in which the extension method is declared must be declared
static
. - The extension method itself must be declared
static
. - The extension method must contain as its first parameter type the keyword
this
,followed by the name of the class it is extending.
static class [Extension Class]
{
public static [Return Type ][Method Name]( this [Class to be Extended] [Identifier])
{
...
}
}
Lets add a method to calculate average to
MyData
class.
static class ExtendMyData { public static double Average( MyData md ) { return md.Sum() / 3; } }
And here's our
Main
method:
class Program { static void Main(string[] args) { MyData md = new MyData(3, 4, 5); Console.WriteLine("Average: "+ ExtendMyData.Average(md) ); } }
The output will be:
Average: 4
0 comments:
Post a Comment