What is the difference between Func and delegate?

Technology CommunityCategory: C#What is the difference between Func and delegate?
VietMX Staff asked 3 years ago
Problem

Consider:

Func<string, string> convertMethod = lambda; // A
public delegate string convertMethod(string value); // B

Are they both delegates? What’s the difference?

The first is declaring a generic delegate variable and assigning a value to it, the second is just defining a delegate type. 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.

Consider:

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!";
    }
}