C# generics type interference strange behaviour -
consider following code :
class program { static void main(string[] args) { var = new a(); var b = new b(); print(a); print(b); console.writeline(b.hello); console.readline(); } static void print<t>(t t) t : { console.writeline(typeof(t)); console.writeline(t.gettype()); console.writeline(t.hello); } } public class { public string hello { { return "helloa"; } } } public class b : { public new string hello { { return "hellob"; } } }
the output got (.net fw 4.5)
- //print(a)
- a
- a
- helloa
- //print(b)
- b
- b
- helloa
- //explicit writeline
- hellob
can explain how got 2nd helloa, expecting hellob ?
public new string hello { { return "hellob"; } }
the new
keyword creates new function happens have same name old one. thus, b
has 2 methods: hello
(a), executed when invoked through variable of compile-time type a
, , hello
(b), executed when invoked through variable of compile-time type b
(or subtype thereof).
since generic parameter t : a
, compiler compiles t.hello
call hello
(a).
b
shadows (or hides) method hello
rather overriding it.
what wanted write was:
public class { public virtual string hello { { return "helloa"; } } } public class b : { public override string hello { { return "hellob"; } } }
note base method declared virtual
, , subclass method override
.
Comments
Post a Comment