Delegates and Functional C# example again using Extension Methods

public class Planet
{
    public string Name { get; set; }
}

public static Planet AddXtoName(this Planet o)
{
    o.Name = o.Name + "X";
    return o;
}

public static Planet AddYToName(this Planet o)
{
    o.Name = o.Name + "Y";
    return o;
}

public static void Execute(this Planet o, Action cmd)
{
    cmd();
}

public static void Execute2(this Planet o, Action<string> cmd)
{
    cmd(o.Name);
}

public static int Execute3(this Planet o, Func<string, int> cmd)
{
    return cmd(o.Name);
}

var px = new Planet();
px.Name = "Jupiter";
px.AddXtoName().AddYToName();

px.AddYToName().AddXtoName();
px.Execute(() =>
{
    Console.WriteLine("Execute this!");
});

px.Execute2((x) =>
{
    Console.WriteLine($"Name of Planet is: {x}");
});

px.Execute2((x) =>
{
    Console.WriteLine($"This is also another execution of Exe2 for Name of: {x}");
});

var len = px.Execute3((x) =>
{
    return x.Length;
});

var len2 = px.Execute3((x) =>
{
    return x.Length + 100;
});

Console.WriteLine(len);
Console.WriteLine(len2);
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 *