I am looking at the code from here
/// <summary>
/// Returns the command that, when invoked, attempts
/// to remove this workspace from the user interface.
/// </summary>
public ICommand CloseCommand
{
get
{
if (_closeCommand == null)
_closeCommand = new RelayCommand(param => this.OnRequestClose());
return _closeCommand;
}
}
what does param in param => this.OnRequestClose() refer to?
RelayCommand is presumably a delegate-type that accepts a single parameter, or a type that itself takes such a delegate-type in the constructor. You are declaring an anonymous method, saying simply "when invoked, we'll take the incoming value (but then not use it), and call OnRequestClose. You could also have (maybe clearer):
_closeCommand = new RelayCommand(delegate { this.OnRequestClose(); });
It is probably clearer in other uses where it is used, for example:
var ordered = qry.OrderBy(item => item.SomeValue);
where the lambda is "given an item, obtain the item's SomeValue". In your case the lambda is "given param, ignore param and call OnRequestClose()"
param => this.OnRequestClose() is lambda
Func<sometype_that_param_is,sometype_that_OnRequestClose_Is>
or
Action
I'm not sure which
So it's just an expression for a func that is called by something, that will pass an argument which will be 'param' an then not used
Nothing. The line defines a lambda expression representing a function. That function have a signature like: Foo(T param) where T will be a specific type infered by the compiler based on the type of the argument of the construtor being called.
param is the only parameter of your lambda expression ( param=>this.OnRequestClose() )
As you are instantiating an ICommand object, param would probably contain the parameter passed to this ICommand from the UI. In your case, the parameter is not used in the command (it does not appear on the right side of the lambda expression).
Related
I am trying to stub a method that has an out paramteter using RhinoMock's Do method, but I keep getting the message cannot resolve symbol outParam. Here's the stubbing part:
private static void FakeClientsLoading(MyClass fakeClass, IEnumerable<string> clientsToLoad)
{
fakeClass.Stub(
x =>
x.LoadClientsFromDb(Arg<string>.Is.Anything,
out Arg<object>.Out(null).Dummy))
.Do(
new LoadClientsFromDbAction(
(someString, out outParam ) =>
TestHelper.LoadClients(someString, clientsToLoad)));
}
And here is my custom delegate declaration:
public delegate void LoadClientsFromDbAction(string s, out object outParam);
What I'd like to achieve is to run the test helper method whenever LoadClientsFromDb is invoked. From my understanding outParam should be mapped to whatever is passed as the out parameter to the called method, but it doesn't seem to work this way.
It seems that I have finally found the answer to my question. It turns out that, quoting section 26.3.1 from this link:
Specifically, a delegate type D is compatible with an anonymous method
or lambda-expression L provided:
If L is a lambda expression that has an implicitly typed parameter list, D has no ref or out parameters.
This means that you need an explicitly typed parameter list in order to create a lambda with an out parameter.
That's not all, though. It is still necessary to assign a value to the out parameter upon exiting the anonymous method.
The final and working code:
private static void FakeClientsLoading(MyClass fakeClass, IEnumerable<string> clientsToLoad)
{
fakeClass.Stub(
x =>
x.LoadClientsFromDb(Arg<string>.Is.Anything,
out Arg<object>.Out(null).Dummy))
.Do(
new LoadClientsFromDbAction(
(string someString, out object outParam) =>
{
outParam = null;
TestHelper.LoadClients(someString, clientsToLoad);
}
));
}
I was reading some code and saw the following:
Method.Find(delegate(Department depts) {
return depts.Id == _departmentId; });
The T Find method has the following description:
public T Find(Predicate<T> match);
// Summary:
// Searches for an element that matches the conditions defined by the specified
// predicate, and returns the first occurrence within the entire
// System.Collections.Generic.List<T>.
//
// Parameters:
// match:
// The System.Predicate<T> delegate that defines the conditions of the element
// to search for.
// (...)
Is it possible to rewrite this method to take a lambda expression as a parameter, and if so, how?
The method can already accept a lambda expression as a parameter, if you want to pass one to it.
The method simply indicates that it accepts a delegate. There are several ways of defining a delegate:
A lambda (Find(a => true))
An anonymous delegate (what you used in your example)
A method group Find(someNamedMethod)
Reflection (Find((Predicate<Whatever>)Delegate.CreateDelegate(typeof(SomeClass), someMethodInfo)))
No need to re-write the method, you can use a lambda already, as below:
Method.Find(x => x.Id == _departmentId );
The code you provide is an anonymous delegate
Method.Find(delegate(Department depts) {
return depts.Id == _departmentId; });
a lambda is an anonymous function.
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.
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)
It calls this constructor:
DelegateCommand<T>(Action<T>, Func<T, Boolean>)
Passing a lambda that always returns true as the second parameter
I know what a func is, but not able to understand the following piece of code:
There's a simple property :
public Func<DomainFacade> BusinessFacadeFactory { get; set; }
And this is how the property is set:
this.BusinessFacadeFactory = () => new DomainFacade();
Now this way of setting the property, is it a Anonymous method or something else?
That's called a lambda expression.
It's a more-compact form of an anonymous method.
() => new DomainFacade() is a lambda expression
It is an unnamed method written in place of a delegate
The compiler converts it to a delegate instance
It's real format is
(parameter)=>expression or a statement block
Since the func requires a delegate to be assigned we can write a lambda expression instead of the delegate which would internally get converted to a delegate instance.
So,
() denotes a an empty parameter
new DomainFacade(); is the expression
that internally gets converted to delegate by the compiler
It is a lambda expression, which is shorthand for creating an anonymous method.
()
is the input parameters (i.e. none)
new DomainFacade();
is the method body.
() => new DomainFacade() is a lambda expression.
It is an inline method, returned as a delegate value.
This is a lambda expression as others have said. Here is what it would break down like this in long form:
this.BusinessFacadeFactory = () => new DomainFacade();
then
this.BusinessFacadeFactory = new delegate(){ return new DomainFacade()};
then
...
BusinessFacadeFactory = OnBusinessFacadeFactory;
...
private DomainFacade OnBusinessFacadeFactory()
{
return new DomainFacade()
}
I was going through Jeffrey Palermo's book and came across this syntax.
private void InitializeRepositories()
{
Func<IVisitorRepository> builder = () => new VisitorRepository();
VisitorRepositoryFactory.RepositoryBuilder = builder;
}
What does it mean?
() => indicates a lambda expression that takes no arguments.
In general, it means a function with no arguments.
In this particular example, it creates an anonymous function with no arguments that returns a new VisitorRepository(); object every time.
Func<IVisitorRepository> stands for a delegate which takes no arguments and returns a IVisitorRepository. The creation of that delegate is a lambda function:
() //means no parameters
=> new VisitorRepository()// means it returns a new VisitorRepository
() is the place where you place your variables
Example a common event handled would look like (sender, args)
=> // means throw these parameter into this method
after => you can either drop a one line execution thing like new VisitorRepositor()
OR
you can place a whole function like
Func<IRepository> = (sender, args) =>
{
var myObject = (SomeObject)sender;
return new VisitorReposiroty { id = myObject.SomeId };
}
As other stated it's lambda expression and it really clears your code from method or function that handle a specific event.
Once you read them good it's really damn useful.
The () => syntax is a lambda expression. Lambdas were introduced in C# 3.0 and are used to define an anonymous method for a delegate.
The delegate is defined using the generic Func. So in this case the signature for the delegate is: no input parameters and one output parameter of type IVisitorRepository.
So on the left side of the => lambda array are the names of the input parameters. In case of no input parameters just write (). On the rightside of the => lambda is the code to return the output parameter, in this example: new VisitorRepository().
I suggest read more about lambda expressions in C# to fully understand this code. There is also a generic delegate involved, so you need understanding of Generics and Delegates as well.
Func is a delegate without parmeter and with an IVisitorRepository return value.
() => is a lambda expression creating an anonymous method.
new VisitorRepository() is the content of this anonymous method.
so this line is creating a delegate which is pointing to a anonymous method, which is returning an instance of VisitorRepository.
Func<IVisitorRepository> builder = () => new VisitorRepository()
In the next line, you set the value of a static property to this just created delegate.
VisitorRepositoryFactory.RepositoryBuilder = builder;
After this you can use the property to call the anonymous method, which is creating a new instance of VisitorRepository.
IVisitorRepository repository = VisitorRepositoryFactory.RepositoryBuilder();
In this case, repository will be an instance of VisitorRepository.
It means a function takes no parameters, like:
delegate() {//}