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.
An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.
A Delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++.
Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.
The Func delegate takes zero, one or more input parameters, and returns a value (with its out parameter). Action takes zero, one or more input parameters, but does not return anything. Predicate is a special kind of Func.
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:
public static class Program { // you can define your own delegate for a nice meaningful name, but the // generic delegates (Func, Action, Predicate) are all defined already public delegate string ConvertedMethod(string value); public static void Main() { // both work fine for taking methods, lambdas, etc. Func<string, string> convertedMethod = s => s + ", Hello!"; ConvertedMethod convertedMethod2 = s => s + ", Hello!"; } }
But more to the point, both Func<string,string>
and delegate 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With