Delegates are methods that you can use as variables, like strings etc. For example you can declare a delegate method with one argument:
delegate void OneArgumentDelegate(string argument);
It doesn't do anything, much like an interface. If you have a method in any class with one argument like this:
void SomeMethod(string someArgument) {}
It matches the signature of the delegate, and thus can be assigned to a variable of its type:
OneArgumentDelegate ThisIsAVariable = new OneArgumentDelegate(SomeMethod);
OneArgumentDelegate ThisIsAlsoAVariable = SomeMethod; // Shorthand works too
These can then be passed as arguments to methods and invoked, like so:
void Main()
{
DoStuff(PrintString);
}
void PrintString(string text)
{
Console.WriteLine(text);
}
void DoStuff(OneArgumentDelegate action)
{
action("Hello!");
}
This will output Hello!
.
Lambda expressions are a shorthand for the DoStuff(PrintString)
so you don't have to create a method for every delegate variable you're going to use. You 'create' a temporary method that's passed on to the method. It works like this:
DoStuff(string text => Console.WriteLine(text)); // single line
DoStuff(string text => // multi line
{
Console.WriteLine(text);
Console.WriteLine(text);
});
Lambda expressions are just a shorthand, you might as well create a seperate method and pass it on. I hope you understand it better now ;-)