Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Function Using Unknown Parameter

Tags:

c#

lambda

I see PRISM declaring the following constructor, and I don't understand what's that "o" being used with the lambda function that serves as the second parameter when the base constructor is called:

public DelegateCommand(Action<T> executeMethod)
    : this(executeMethod, (o)=>true)
{            
}

I'd appreciate an explanation.

like image 221
Ofer Avatar asked Sep 16 '13 13:09

Ofer


2 Answers

The constructor which declaration you posted calls another constructor, so to explain it, we should first look at the other constructor’s signature:

public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)

So the second parameter is a Func<T, bool>. That means it is a function that takes a parameter of type T and returns a boolean.

Now if you look at the lambda that is used:

(o) => true

Lambdas in general have the syntax (parameter-list) => lambda-body, so in this case, the single parameter of the lambda is a variable o (which type is inferred to be T) and the function returns a constant result true.

The purpose of this is to basically make a command that is always executable.

Of course that lambda could look a lot more complicated, so when using the DelegateCommand, you are likely to use more complex and non-constant expressions. For example:

 new DelegateCommand(DoSomething, o => o.SomeProperty >= 0 && o.SomeProperty < 10 && o.SomeBoolProperty)
like image 68
poke Avatar answered Oct 03 '22 17:10

poke


It calls this constructor:

DelegateCommand<T>(Action<T>, Func<T, Boolean>)

Passing a lambda that always returns true as the second parameter

like image 35
Matthew Mcveigh Avatar answered Oct 03 '22 16:10

Matthew Mcveigh