What is the name for this usage of delegate in C#? - 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);

Related

Does `this.SomeMethod` passed as Func argument capture `this`?

If a method asks for some Func:
void Foo(Func<string> stringFactory);
Then passing a lambda referencing this introduces variable capturing:
Foo(() => this.MagicStringProperty); // Captures `this`
Does this happen also when passing an instance method instead of a lambda?
Foo(this.GetMagicString); // Capturing??
string GetMagicString()
{
return "Bar";
}
If so, is this compiled to a similar thing as the lambda version?
If not, how does it manage to pass both the method (which exists somewhere) and the instance (which exists somewhere else)?
this doesn't have to be captured in a closure here. The difference between the calls is that there is a compiler generated method for () => this.MagicStringProperty(). This method simply calls this.GetMagicString().
If you decompile the code you will see that Foo(this.GetMagicString) translates to this.Foo(new Func<string>((object) this, __methodptr(GetMagicString))) and that Foo(() => this.GetMagicString()) translates to this.Foo(new Func<string>((object) this, __methodptr(<.ctor>b__1_0))) where <.ctor>b__1_0 is the compiler generated method that calls this.GetMagicString():
[CompilerGenerated]
private string <.ctor>b__1_0()
{
return this.GetMagicString();
}

Extension method on lambda expression

I have a helper method which gets the name of a property defined by a lambda which works as below:
ExpressionUtil.GetName((Thing t) => t.Property); // returns "Property"
I would like to turn this into an extension method so the syntax would be of the form:
((Thing t) => t.Property).GetName(); // wont compile : operator '.' cannot be applies to operand of type 'lambda expression'
However I cant seem to do this as ((Thing t) => t.Property) is a lambda (not an expression or Func yet). Is there any way to write an extension method which applies directly to a lambda? If not why is this a bad thing to do?
You can't do that, because a lambda expression has no type by itself; its type is determined by the context (e.g. if you assign it to a delegate variable or pass it as an argument to a method).
Since ((Thing t) => t.Property) doesn't have a type, you can't call an extension method on it, because the compiler doesn't know which extension methods are valid candidates.
You can, however, declare a variable and call the extension method on it:
Func<Thing, OtherThing> func = t => t.Property;
string name = func.GetName();
you may create an extension method on an Action at the low cost of having a introducing instantiation.
I sometimes use it and the code is readable.
The reason this code exists is less elegant, a rotten NAS :-[
new Action(() =>
{
if (File.Exists(newFullPath))
File.Delete(newFullPath);
File.Move(oldFullPath, newFullPath);
})
.Try(attemps: 2, exceptionValidator: (exception, attempt, attempts) =>
{
var throwIt = (attempt == attempts);
if (!throwIt)
Thread.Sleep(500);
// .. tracing ./. throw
return (throwIt);
});
Just in case ... even if post not young.

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 does this mean in C# or LINQ? - ( () => )

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

What does the operator '=>' mean in C#?

What does the '=>' in this statement signify?
del = new SomeDelegate(() => SomeAction());
Is the above declaration the same as this one?
del = new SomeDelegate(this.SomeAction);
Thanks.
Basically it's specifying an anonymous function, that takes no parameters that calls SomeAction. So yes, they are functionally equivalent. Though not equal. Using the lambda is more equivalent to:
del = new SomeDelegate(this.CallSomeAction);
where CallSomeAction is defined as:
public void CallSomeAction()
{
this.SomeAction();
}
Hope that helps!
The "=>" can be read "goes to" (source: Eric Lippert), and simply separates the argument(s) from the operation in a lambda expression. In this case, a lambda is overkill. Better examples would be:
var subList = list.FindAll(item => item.Type == "Foo");
(find all items where the item's type is Foo)
etc. In C# 2.0, this can also be written:
var subList = list.FindAll(delegate(SomeType item) {
return item.Type == "Foo";});
And is a quick way of expression a function "inline", while also offering "closure" support - i.e. it could also be:
string itemType = ...
var subList = list.FindAll(item => item.Type == itemType);
To do this otherwise would require a type-definiton to pass in the item-type:
class Searcher {
public string itemType;
public bool Find(SomeType item) {return item.Type == itemType;}
}
...
Searcher searcher = new Searcher();
searcher.itemType = ...
var subList = list.FindAll(searcher.Find);
In fact, this is pretty-much exactly what the compiler does for us (both for "delegate" and lambda usage). The biggest difference is that a lambda can also express an Expression, for example for LINQ.
They do the same thing but the "() => ..." syntax is what is called a lambda expression and as such is the same as an anonymous function. You could probably leave out the delegate part altogether and just let the compiler infer the delegate type for you.
del = this.SomeAction;
Depending on what type "del" is seclared as.
Edit
Using lambdas or anonymous methods or just a regular method for starters enables you to map methods that didn't have the delegate's signature to the delegate.
For example, say you have a delegate with the signature bool myDelegate(int, int) but you wanted to have a method with the signature bool myMethod(string, string) handle the delegate. You could then use the lambda expression to let you do this inline with a short syntax like so.
delegate bool myDelegate(int x, int y);
// With lambdas...
myDelegate del = (int a, int b) => myMethod(a.ToString(), b.ToString());
// With anonymous methods...
myDelegate del2 = delegate(int a, int b) { return myMethod(a.ToString(), b.ToString()); };
// The good ol' way without lambdas or anonymous methods...
myDelegate del3 = SomeDelegateHandler;
... then write a method somewhere else ...
// Handler method
private bool SomeDelegateHandler(int a, int b)
{
return myMethod(a.ToString(), b.ToString());
}
So as you can see lambdas and anonymous methods are basically just a shorter/inline way of making a method to handle the delegate. In you case you might not need to make an extra method. It just depends on if the delegate signature is the same as your method signature, and to me, it seems like it is.
=> is the Lambda Operator, lambda expressions are like an evolution of the C# 2.0 anonymous methods.
You can use anonymous methods and lambda expressions in a very similar way to create delegate instances:
Func<string,int> wordCount;
wordCount = delegate (string text) { return text.Split().Length; };
Console.WriteLine (wordCount("Hello World"));
Using lambda expressions:
Func<string,int> wordCount;
wordCount = (string text) => { text.Split().Length; };
Console.WriteLine (wordCount("Hello World"));

Categories

Resources