4

Possible Duplicate:
Compilation fails if delegate definitions is put in another project?

Using .NET 3.5 SP1 and Visual Studio 2008

Projects A and B, both class libraries, A uses B In project B i have the following:

public delegate void MyDelegate(object o1, EventArgs o2);
public delegate T MyUberDelegate<T>(MyDelegate myDelegate);

public class MyTestClass
{
    private MyUberDelegate<EventHandler> uberDelegate;
    public MyTestClass()
    {
        uberDelegate = h => (s, e) => h(s, e);
    }
}

This compiles, no problems. (uberDelegate returns an EventHandler which calls MyDelegate)

If i copy MyTestClass to project A, i get the following compile errors:

Error   1   Cannot convert lambda expression to delegate type 'MyUberDelegate<System.EventHandler>' because some of the return types in the block are not implicitly convertible to the delegate return type
Error   2   Delegate 'MyDelegate' does not take '2' arguments

If i alter MyTestClass to also include a field of type MyDelegate, it does work:

public class MyTestClass
{
    private MyUberDelegate<EventHandler> uberDelegate;
    private MyDelegate myDelegate;

    public MyTestClass()
    {
        uberDelegate = h => (s, e) => h(s, e);
    }
}

Why?

EDIT: duplicate of Compilation fails if delegate definitions is put in another project?

Community
  • 1
  • 1
Bubblewrap
  • 7,266
  • 1
  • 35
  • 33
  • The fix with the MyDelegate field make it look like http://stackoverflow.com/questions/3382231/possible-c-4-0-compiler-error-can-others-verify – H H Aug 31 '10 at 14:16
  • Agree this is a weird one. I notice if you change your line to this it compiles: uberDelegate = h => (s, e) => ((MyDelegate)h)(s, e); – Kirk Woll Aug 31 '10 at 14:22
  • 1
    I also noticed that MyDelegate defines a delegate with the exact same signature as EventHandler. If you comment out the declaration for MyDelegate and modify MyUberDelegate to use EventHandler instead of MyDelegate, it also solves the compiler error. – Kirk Woll Aug 31 '10 at 14:26
  • The signature matches in the question to rule out that a difference in signature is causing the compile error. In the real world it has a different signature. Regarding the cast: it seems that basically any mention of MyDelegate will make it compile, cast or no cast. – Bubblewrap Aug 31 '10 at 14:28
  • @Bubblewrap, yes, I see the behavior you're describing. Very strange. – Kirk Woll Aug 31 '10 at 14:44
  • Interestingly, it seems that consuming MyDelegate from within **any** class in Project A serves to solve the compiler error. (I created a new class in Project A that declared a field of type MyDelegate) – Kirk Woll Aug 31 '10 at 14:52

0 Answers0