I see delegates in two forms:
A. Func<string, string> convertMethod = lambda
B. public delegate string convertMethod(string value);
I'm uncertain of what actually the difference between these two are. Are they both delegates? I believe the first one would use a lambda and the second would have to have a method to actually perform the work. I may be confused too.
A initializes an instance of a delegate (that can be called immediately). It's a variable of type Func< string, string >.
B specifies the definition of a delegate (its signature). It can be used to later define variables of type convertMethod.
From MSDN,
and
You may also be interested in this SO answer on delegate keyword vs lambda expression.
Additionally, MSDN has a good article on Lambda Expressions:
First of all, your two examples are doing two totally separate things. The first is declaring a generic delegate variable and assigning a value to it, the second is just defining a
delegate
type. Your example, more completely, would be:But more to the point, both
Func<string,string>
anddelegate string convertMethod(string)
would be capable of holding the same method definitions whether they be methods, anonymous methods, or lambda expressions.As for which you should use, depends on the situation. If you want your delegate to be defined more by what it takes and returns, then the generic delegates are perfect. If you want the delegate to have some special name that gives more definition of what that delegate should do (beyond simple
Action
,Predicate
, etc) then creating your own delegate is always an option.The code sample you have is confusing things a bit so let me try and clear it up. The following 2 items are delegate declarations. These are easy to spot because they will always contain the
delegate
keywordThis line of code is assigning a value to a local which is typed to a delegate
The above code is not limited to using just lambdas though. The value could also be a compatible method group or another delegate value.
One other item to note is that even though
Func<string, string>
andconvertMethod
are both delegates with identical signatures their values are not convertible to each other. For example the following is illegal