What is Delegate? [closed] Ask Question

What is Delegate? [closed] Ask Question

I am confused that what is the actual role of a delegate?

I have been asked this question many times in my interviews, but I don't think that interviewers were satisfied with my answer.

Can anyone tell me the best definition, in one sentence, with a practical example?

ベストアンサー1

I like to think of a delegate as "a pointer to a function". This goes back to C days, but the idea still holds.

The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose. Delegates come in handy for things like event handlers, and such, where you do different things based on different events, for example.

Here's a reference for C# you can look at:

In C#, for example, let's say we had a calculation we wanted to do and we wanted to use a different calculation method which we don't know until runtime. So we might have a couple calculation methods like this:

public static double CalcTotalMethod1(double amt)
{
    return amt * .014;
}

public static double CalcTotalMethod2(double amt)
{
    return amt * .056 + 42.43;
}

We could declare a delegate signature like this:

public delegate double calcTotalDelegate(double amt);

And then we could declare a method which takes the delegate as a parameter like this:

public static double CalcMyTotal(double amt, calcTotalDelegate calcTotal)
{
    return calcTotal(amt);
}

And we could call the CalcMyTotal method passing in the delegate method we wanted to use.

double tot1 = CalcMyTotal(100.34, CalcTotalMethod1);
double tot2 = CalcMyTotal(100.34, CalcTotalMethod2);
Console.WriteLine(tot1);
Console.WriteLine(tot2);

おすすめ記事