Is this the wrong code on MSDN?

I found the following code on MSDN ( here ) that seems to be wrong (compile-time error). Is not 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(); 

Class C is not derived from Test , so this assignment will not compile. Something is missing for me (some assumptions that I did not consider in the article?)

Also, the following line will be incorrect even if class C was obtained from the test:

 D cd2 = new D(t.M2); 

Is not it?

+7
c # msdn
source share
1 answer

This line should be

 C t = new C(); 

You can also use (in newer versions of C #)

 var t = new C(); 

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

+5
source share

All Articles