private void StringAction(string aString) // method to be called
{
return;
}
private void TestDelegateStatement1() // doesn't work
{
var stringAction = new System.Action(StringAction("a string"));
// Error: "Method expected"
}
private void TestDelegateStatement2() // doesn't work
{
var stringAction = new System.Action(param => StringAction("a string"));
// Error: "System.Argument doesn't take 1 arguments"
stringAction();
}
private void TestDelegateStatement3() // this is ok
{
var stringAction = new System.Action(StringActionCaller);
stringAction();
}
private void StringActionCaller()
{
StringAction("a string");
}
I don't understand why TestDelegateStatement3
works but TestDelegateStatement1
fails. In both cases, Action
is supplied with a method that takes zero parameters. They may call a method that takes a single parameter (aString
), but that should be irrelevant. They don't take a parameter. Is this just not possible to do with lamda expressions, or am I doing something wrong?
The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.
Lambda expressions are also examples of delegates, which are collections of lines of code that can take inputs and optionally return outputs. We use the type Func<T> to define delegates that return an output, and Action<T> for delegates that will not return an output.
Anonymous methods are basically functions without a name, with the ability to create closures. Lambda expressions are constructs that are convertible to both anonymous methods and expression trees, and follow more complex rules of type inference than anonymous methods.
Lambda expressions, or just "lambdas" for short, were introduced in C# 3.0 as one of the core building blocks of Language Integrated Query (LINQ). They are just a more convenient syntax for using delegates.
As you said, Action doesn't take any parameters. If you do this:
var stringAction = new System.Action(StringAction("a string"));
You actually execute the method here, so that is not a method parameter.
if you do this:
var stringAction = new System.Action(param => StringAction("a string"));
you tell it that your method takes a parameter called param
, which Action does not.
So the correct way to do this would be:
var stringAction = new System.Action( () => StringAction("a string"));
or more compact:
Action stringAction = () => StringAction("a string");
the empty brackets are used to indicate the lambda doesn't take any parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With