1

I have created delegates with the same signature like function passed for Thread class job:

    public delegate void myDelegateForThread();

    static void Main(string[] args)
    {
        myDelegateForThread del = thrFunc;


        Thread t = new Thread( del);
        t.Start();


        for (int i = 0; i < 10000; i++) { Console.WriteLine("Main thread " +i); }

        Console.ReadLine();

    }

    public static void thrFunc()
    {
        for (int i = 0; i < 10000; i++) { Console.WriteLine("Secondary thread " + i); }
    }

But compiler is not happy I don't pass ThreadStart for Thread constructor. I know how to solve problem in this case, but my question is can I do typecast for delegates if they have the same signature?

vico
  • 17,051
  • 45
  • 159
  • 315

1 Answers1

0

If you mean the following, no it does not work:

public delegate int MyDelegate1(double param);
public delegate int MyDelegate2(double param);
public int MyFunction(double p) { return 1; }

MyDelegate1 del1 = MyFunction;
MyDelegate2 del2 = (MyDelegate2)del1;

The delegate is in that way the same as any other type and there is no inheritance or interface relation -> they can't be typecasted to each other even if the signature matches.

What does work is wrapping it in a new delegate:

MyDelegate2 del2 = new MyDelegate2(del1);
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113