Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a Wrong Code in MSDN?

Tags:

c#

msdn

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?

like image 760
Kamran Bigdely Avatar asked May 28 '14 20:05

Kamran Bigdely


People also ask

What is system error code?

A system error code is an error number, sometimes followed by a short error message, that a program in Windows may display in response to a particular problem it's having.


1 Answers

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.

like image 68
Ben Voigt Avatar answered Sep 29 '22 21:09

Ben Voigt