Following is an example use of an Extension method in C#.
Imagine you have a class written by someone else and you are
not allowed to do any modification to the class.
public class Class1
{
public int MyProperty { get; set; }
}
You have come up with the following calculation and want to
have it in the Class1, so that others could use it without rewriting the
calculation.
int sum = p.MyProperty * 5;
Now, incomes the extension method.
public static class myextention
{
public static int test(this Class1 p)
{
return p.MyProperty * 5;
}
}
After creating the extension method, you can now call the test function as it’s defined in the Class1 itself.
Class1 c = new Class1();
int extensionSum = c.test();
No comments:
Write comments