Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can someone tell me the advantages of using a delegate as opposed to calling the function itself as shown below (or in other words why choose Option A over Option B)? I was looking at someone's linq code last night and they had something similar to Option A but it was being used to return a compiled linq query.

I realize the former can now be passed around to other functions.. just not sure of its practicality. BTW, I realize this wouldn't compile as-is.. uncommented one of the functions before posting. TYIA

class Program
{
    static void Main(string[] args)

    {   
        Console.WriteLine(SayTwoWords("Hello", "World"));
        Console.ReadKey();
    }

    // Option A
    private static Func<string, string, string>
        SayTwoWords = (a, b) => String.Format("{0} {1}", a, b);

    // Option B
    private static string SayTwoWords(string a, string b)
    {
        return String.Format("{0} {1}", a, b);
    }        
}

************EDIT************

Not sure if it explains my question better but here is an example of the type of code that originally got me thinking about this:

public static class clsCompiledQuery
{
    public static Func<DataContext, string, IQueryable<clsCustomerEntity>>
        getCustomers = CompiledQuery.Compile((DataContext db, string strCustCode)
            => from objCustomer in db.GetTable<clsCustomerEntity>()
            where objCustomer.CustomerCode == strCustCode
            select objCustomer);
}

Is there any advantage to writing a function in this way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
350 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is no advantage in the code you posted. In your code, using the delegate just adds complexity as well as an extra runtime cost - so you're better off just calling the method directly.

However, delegates have many uses. "Passing around" to other methods is the primary usage, though storing a function and using it later is also very useful.

LINQ is built on top of this concept entirely. When you do:

var results = myCollection.Where(item => item == "Foo");

You're passing a delegate (defined as a lambda: item => item == "Foo") to the Where function in the LINQ libraries. This is what makes it work properly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...