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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With