-2

How can I use function as parameter of another function and assign it to a delegate

public class myClass
{
    public delegate void myDelegate(double x, string s);
    //declaration of   delegate
    public void func(double x, string s)
    {
      dosomethings...
    }
    // what is the declaration of the argument 'Function declaration'
    public void myFunction('Function declaration' function)
    { 
      myDelegate deFunc;
      deFunc = function;
    }
    }
    static void Main(string[] args)
    {
        myFunction(func);
    }
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
rachid
  • 5
  • 2

2 Answers2

1

Main is static so another method should be static too in this case. For example:

    public delegate void myDelegate(double x, string s);
    //declaration of   delegate
    public static void func(double x, string s)
    {
        //dosomethings...
    }
    // what is the declaration of the argument 'Function declaration'
    public static void myFunction(myDelegate function)
    {
        myDelegate deFunc;
        deFunc = function;
    }

    static void Main(string[] args)
    {
        myFunction(func);
    }
fdafadf
  • 809
  • 5
  • 13
1

You can either use the definition you allready provided in your class:

public void myFunction(myDelegate del)
{ ... }

or the Action-delegate introduces in .NET 3.5 which is a shortcut for a delegate returning nothing (void):

public void myFunction(Action<double, string> del)

In the latter case also deFunc within your method should be of type Action<double, string> as you can´t cast that to myDelegate.

Be aware that delegate is a reserved keyword, so you should name your parameter within the methods signature different, e.g. del or just func or @delegate with the verbatim @ in front

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111