7

I found the following code in MSDN (here) which appears to be wrong (compile-time error). Isn't it?

delegate void D(int x);
class C
{
   public static void M1(int i) {...}
   public void M2(int i) {...}
}
class Test
{
   static void Main() { 
      D cd1 = new D(C.M1);      // static method
      Test t = new C();         // <---- WRONG-------
      D cd2 = new D(t.M2);      // instance method
      D cd3 = new D(cd2);      // another delegate
   }
}

Consider this line:

Test t = new C();

The class C is not derived from the class Test, so this assignment will not compile. Am I am missing something here (some assumptions that I have not considered in the article?)

Also the following line would be wrong even if C class was derived from Test:

D cd2 = new D(t.M2);

Isn't it?

Kamran Bigdely
  • 7,946
  • 18
  • 66
  • 86
  • 1
    Yes, it's clearly wrong. Look at the next example: http://msdn.microsoft.com/en-us/library/aa664605(v=vs.71).aspx, they use C c = new C(); there. – empi May 28 '14 at 20:42

1 Answers1

5

That line should be

C t = new C();

You could also use (in new versions of C#)

var t = new C();

The only way that t.M2 on the next line will be valid is if t has type C.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Given that that version of the page is referring to Visual Studio .NET 2003, it would be the former and not the latter. See http://msdn.microsoft.com/en-us/library/bb383973%28v=vs.90%29.aspx – ClickRick May 28 '14 at 21:02
  • 1
    @ClickRick: Well, we don't know what version of C# kami is using, but I agree that `var` wouldn't have been appropriate for that section of MSDN. Edited to clarify. – Ben Voigt May 28 '14 at 21:06