Skip to content

Instantly share code, notes, and snippets.

@mkropat
Created December 12, 2017 19:58
Show Gist options
  • Save mkropat/6592e3f42e9ee7a890bbbd6190da799f to your computer and use it in GitHub Desktop.
Save mkropat/6592e3f42e9ee7a890bbbd6190da799f to your computer and use it in GitHub Desktop.
<Query Kind="Program" />
void Main()
{
Console.WriteLine("## firstAction + secondAction ##");
Action<string> firstAction = x => Console.WriteLine($"firstAction({x})");
Action<string> secondAction = x => Console.WriteLine($"secondAction({x})");
(firstAction + secondAction)("derp");
Console.WriteLine();
// Output:
// firstAction(derp)
// secondAction(derp)
Console.WriteLine("## firstAction + secondAction - firstAction ##");
(firstAction + secondAction - firstAction)("derp");
Console.WriteLine();
// Output:
// secondAction(derp)
Console.WriteLine("## add1Twice(5) ##");
Func<int, int> add1 = x =>
{
Console.WriteLine($"add1({x})");
return x + 1;
};
Func<int, int> add1Twice = add1 + add1;
Console.WriteLine(add1Twice(5));
Console.WriteLine();
// Output:
// add1(5)
// add1(5)
// 6
Console.WriteLine("## with a delegate ##");
NumToNum add2 = x => x + 2;
NumToNum add2Twice = add2 + add2;
Console.WriteLine(add2Twice(5)); // Output: 7
Console.WriteLine();
Console.WriteLine("## exceptions ##");
Action<string> throwsAction = x => throw new Exception("kaboom");
Action<string> printAction = x => Console.WriteLine($"printAction({x})");
try
{
(throwsAction + printAction)("derp");
}
catch (Exception ex)
{
Console.WriteLine($"Caught exception: {ex}");
}
Console.WriteLine();
// Output:
// Caught exception: System.Exception: kaboom
Console.WriteLine("## events ##");
onDerpEvent += x => Console.WriteLine($"before throw: {x}");
onDerpEvent += x => throw new Exception("kaboom");
onDerpEvent += x => Console.WriteLine($"after throw: {x}");
try
{
onDerpEvent("foo");
}
catch (Exception ex)
{
Console.WriteLine($"Caught exception: {ex}");
}
Console.WriteLine();
// Output:
// before throw: foo
// Caught exception: System.Exception: kaboom
}
delegate int NumToNum(int x);
event Action<string> onDerpEvent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment