majkel323
majkel323

Reputation: 23

Delegate : method name expected

interface IDrawable{
    void Draw();
    double ReturnArea(Delegate del);
}


public double ReturnArea(Delegate del){
       return del();
}

del() is highlighted and I am receiving "Method name expected". Basically my question is how can i get this interface method to take as argument delegate which let me use whatever functionality they will provide in methods?

Upvotes: 0

Views: 1214

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37050

You didn´t specify the delegates return-value or its parameters. When using Delegate the actual methods signature isn´t known at compile-time. Thus when invoking it, there´s no way for the compiler to infer the right types, neither for the return-value nor for its arguments. Thus you could provide any delegate to your ReturnArea-method. Thus even the following would be valid:

ReturnArea(() => Console.WriteLine("this method doesn´t return anything"));

However when you know the actual types at compile-time, there´s no reason to stay on the generic Delegate. You can use a strongly-typed delegate instead, e.g. Func<double>:

interface IDrawable
{
    void Draw();
    double ReturnArea(Func<double> del);
}

//...

public double ReturnArea(Func<double> del)
{
   return del();
}

If you really need to use the generic approach with Delegate you have to write this instead:

public double ReturnArea(Func<double> del)
{
   return del.DynamicInvoke();
}

Upvotes: 1

Related Questions