Example of Functional C# using extension Methods

public class Calculor {
    public int Total { get; set; }
}
public class Calculator {
    public int Total { get; set; }
}

public static Calculator Add(this Calculator c, int number) {
    c.Total += number;
    return c;
}
public static Calculator Minus(this Calculator c, int number) {
    c.Total -= number;
    return c;
}
public static Calculator Times(this Calculator c, int number) {
    c.Total *= number;
    return c;
}
public static Calculator Divide(this Calculator c, int number) {
    c.Total = c.Total / number;
    return c;
}

var c = new Calculator();
c.Add(100).Add(50);

Console.WriteLine(c.Total);
150
c.Minus(30);
Console.WriteLine(c.Total);
120
public static object Addx<T>(this T c, int number) {
    object obj = (object)c;

    var p = obj.GetType().GetProperty("Total");
    object itemValue = p.GetValue(obj, null);
    int total = (int)itemValue;
    total += number;
    p.SetValue(obj, total, null);
    return obj;
}

var cc = new Calculator();
cc.Addx<Calculator>(888);
Console.WriteLine(cc.Total);

Console.WriteLine("");
888

public class CalculatorX{
    public int Total { get; set; }
}
var cx = new CalculatorX();
cx.Addx<CalculatorX>(777);
Console.WriteLine(cx.Total);
Console.WriteLine("");
It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *