C# got very interesting feature allowing you to add a method to existing class. Here is what it looks like:
namespace ConsoleApp
{
class A
{
public double value { get; set; }
public A()
{
value = 7.0;
}
}
static class ExtensionMethods
{
public static double ComputeReciprocal(this A a)
{
return 1.0 / a.value;
}
}
class Program
{
static void Main(string[] args)
{
var a = new A();
var value = a.value;
var reciprocal = a.ComputeReciprocal();
}
}
}
C# successfully recognized ComputeReciprocal as A class extension method and let us call it like if it belonged to the class. Please pay attention to extension method parameter list, the first parameter always has to be: this ClassName parameterName, after the first parameter you can add as many additional parameters as you want:
namespace ConsoleApp
{
class Person
{
public string FirstName { get; set; }
public Person()
{
FirstName = "Alex";
}
}
static class ExtensionMethods
{
public static string GetFullName(this Person person, string lastName)
{
return person.FirstName + " " + lastName;
}
}
class Program
{
static void Main(string[] args)
{
var person = new Person();
var fullName = person.GetFullName("Peters");
}
}
}
By the way, it doesn't matter what you call static class which contains your extension methods.
No comments:
Post a Comment