Action l = () => Console.WriteLine(
"Hello, I am a simplest lambda.");
l();
As its the simplest, it got no parameters and doesn't return anything. Ok, now I'mma show you lambda with one parameter:
Action<string> l = (s) => Console.WriteLine(s);
l("Hello, I am a lambda 1 parameter.");
You probably noticed that I omitted parameter type, it's not necessary as type was already specified by the delegate. Well, if you really want it, you can safely put the same type in argument list.
Action<string> l = (string s) => Console.WriteLine(s);
l("Hello, I am a lambda with 1 parameter.");
Now, what about lambdas with multiple parameters?
Action<string, string> l = (s1, s2) => Console.WriteLine(s1 + s2);
l("Hello,", "I am a lambda with 2 parameters.");
Almost forgot, lambdas can have bodies too:
Action<string, string> l = (s1, s2) =>
{
Console.WriteLine(s1 + s2);
};
l("Hello,", "I am a lambda with 2 parameters.");
If you need lambdas returning some kinda value you need different delegate:
Func<int> l = () => { return 7; };
Func delegate may have parameters too, just like Action:
Func<int, int> l = (i) => { return i; };
Func<int, int> l = i => i;
No comments:
Post a Comment