What does this mean in C# or LINQ? - ( () => ) - c#

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() {//}

Related

How to stub a method with out parameter using custom delegate?

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);
}
));
}

How to change delegate expression to lambda?

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.

Not able to understand func<Type> code

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()
}

What is wrong with new Action(() => someCombobox.Text = "x" )

When I write in my code
Action(() => someCombobox.Text = "x" )
I get this error:
Delegate 'System.Action<object>' does not take 0 arguments
Why?
This question is related to this one. I just want to understand why this error occurs.
You do not have to pass that as a constructor parameter:
Action a = () => someCombobox.Text = "x";
All you have to do is to declare an action and then use lambda expression to create it.
Alternatively you can pass the string to the action:
Action<string> a = (s) => someCombobox.Text = s;
a("your string here");
If you wish to create a System.Action delegate which has no parameters and does not return a value, simply change your code to this, removing the new Action([body]):
Action newAction = () => someCombobox.Text = "x";
This is because the lambda expression will return a new parameterless System.Action delegate for you. EDIT: as noted by Aliostad, () => someCombobox.Text = "x" will return either a lambda expression or an Action, depending on the type of the variable you are assigning it to.
EDIT: as Darin says, if you wish it to accept an argument then you need to pass that in when creating the lambda expression.
I think the answer here is the same as in the related question you are linking to: .NET 2.0 only has a definition for an Action delegate that takes a parameter.
The parameterless Action delegate was added in .NET 3.5, and requires a reference to System.Core.

What is the name for this usage of delegate in C#?

This is a terminology question. In C#, I can do this:
delegate Stream StreamOpenerDelegate(String name);
void WorkMethod(StreamOpenerDelegate d)
{
// ...
}
void Exec1()
{
WorkMethod((x) =>
{
return File.OpenRead(x);
});
}
void Exec2()
{
StreamOpenerDelegate opener = (x) =>
{
return File.OpenRead(x);
};
WorkMethod(opener);
}
Q1
The Exec1() method demonstrates the use of an anonymous delegate, correct?
Q2
Inside Exec2(), would opener
be considered an anonymous delegate? It does have a name. If it's not an anonymous delegate, what should I call it? Is there a name for this syntax? "named anonymous delegate?" a local variable holding an anonymous delegate?
Q1: There's no such term as "anonymous delegate" (in the C# language specification) - but this uses a lambda expression which is one kind of anonymous function. See section 7.14 of the C# language specification for details.
Q2: opener is a variable. The variable is assigned a value created using a lambda expression. After it's been created, the delegate is just an instance of StreamOpenerDelegate. In other words, the concepts of lambda expression, anonymous function and anonymous method are source code concepts rather than execution time concepts. The CLR doesn't care how you created the delegate.
By the way, both of your lambda expressions can be expressed more concisely - fewer parentheses etc:
void Exec1()
{
WorkMethod(x => File.OpenRead(x));
}
void Exec2()
{
StreamOpenerDelegate opener = x => File.OpenRead(x);
WorkMethod(opener);
}
alternatively you could just use a method group conversion:
StreamOpenerDelegate opener = File.OpenRead;
No and no.
A1: This feature is new to C# 3.0 and is called a lambda expression. C# 2.0 has a similar feature called anonymous methods; for example:
button.Click += delegate {
//code
};
A2: opener is a regular variable that happens to hold a lambda expression.
By the way, a lambda expression that takes exactly one parameter doesn't need parentheses. Also, a lambda expression that consists only of a return statement doesn't need braces.
For example:
StreamOpenerDelegate opener = x => File.OpenRead(x);

Categories

Resources