Reputation:
Reading this line of code example from a book:
Func<string,int> returnLength;
returnLength = delegate (string text) { return text.Length; };
Console.WriteLine(returnLength("Hello"));
It says
Func<string,double,int>
is equivalent to a delegate type of the formpublic delegate int SomeDelegate(string arg1, double arg2)
So Func
is a delegate? Then what is that delegate we have defined again in the code example?
We define a variable from a Func
that is like a delegate
and then assign it again to another delegate
? I am super confused and can't understand this concept. :(
Can someone explain it?
Upvotes: 2
Views: 638
Reputation: 125610
So Func
is a delegate?
Yes, it's defined as follows:
public delegate TResult Func<in T, out TResult>(T arg)
It's described as:
Encapsulates a method that has one parameter and returns a value of the type specified by the
TResult
parameter.
Read Func Delegate for more.
Then what is that delegate we have defined again in the code example?
That's the anonymous method we create to assign it to the Func
-typed variable. You could use named method or lambda expression as well, as long as the input and return types match the Func
generic parameters.
We define a variable from a Func that is like a delegate and then assign it again to another delegate?
No, we create a variable typed as Func<string, int>
and then create a delegate matching that type and assign it to the variable.
Additional sources from MSDN:
Upvotes: 4
Reputation: 15865
Your code can also be expressed like this:
Func<string,int> returnLength = delegate (string text) { return text.Length; };
Console.WriteLine(returnLength("Hello"));
A func is a delegate.
Func<string, int>
is the declaration, delegate (string text) { return text.Length; }
is the function that you are assigning.
string text
) and returns an integer (return text.Length;
).This would return 5
as the text.Length of "Hello" is 5. It is not as you are creating 2 delegates in this example, rather you are just assigning one.
Upvotes: 1
Reputation: 12683
Yes a Func
is equivalent to a delegate
type with a return type. The delegate
you have defined is the delegate
that is executed when the method is called returning the int
type.
This can be shortcutted down to
Func<string, int> returnLength = (text) => { return text.length; };
In this situation the delegate returns a value type of int (Int32)
Now Action is also a delegate type without a return value such as.
Action<string> action = delegate(string text) { text = ""; };
or
Action<string> action = (text) => { text = ""; };
Now anonymous types are much different than a delegate
, Action
or Func
. Now Func
& Action
were implemented in .Net 3.5 after delegates were introduced.
Upvotes: 1
Reputation: 3850
the same code you could just write
Func<string,int> returnLength = (s) => {return s.Length;}
assigning delegate to a Func
is just like assigning a variable to another..
Upvotes: 1