.net - Question about C# 4.0's generics covariance -
having defined interface:
public interface iinputboxservice<out t> { bool showdialog(); t result { get; } }
why following code work:
public class stringinputboxservice : iinputboxservice<string> { ... } ... iinputboxservice<object> service = new stringinputboxservice();
and doesn't?:
public class integerinputboxservice : iinputboxservice<int> { ... } ... iinputboxservice<object> service = new integerinputboxservice();
does have int being value type? if yes, how can circumvent situation?
thanks
yes, absolutely has int
being value type. generic variance in c# 4 works reference types. because references have same representation: reference reference, clr can use same bits knows string reference object reference. clr can make sure code safe, , use native code knows iinputboxservice<object>
when passed iinputboxservice<string>
- value returned result
representationally compatible (if such term exists!).
with int
=> object
there have boxing etc, don't end same code - messes variance.
edit: c# 4.0 spec says in section 13.1.3.2:
the purpose of variance annotations provide more lenient (but still type safe) conversions interface , delegate types. end definitions of implicit (§6.1) , explicit conversions (§6.2) make use of notion of variance-convertibility, defined follows: type t variance-convertible type t if t either interface or delegate type declared variant type parameters t, , each variant type parameter xi 1 of following holds:
xi covariant , implicit reference or identity conversion exists ai bi
xi contravariant , implicit reference or identity conversion exists bi ai
xi invariant , identity conversion exists ai bi
this doesn't make terribly obvious, reference conversions exist between reference types, leaves identity conversions (i.e. type itself).
as workarounds: think you'd have create own wrapper class, basically. can simple as:
public class wrapper<t> { public t value { get; private set; } public wrapper(t value) { value = value; } }
it's pretty nasty though :(
Comments
Post a Comment