Having defined this interface:
public interface IInputBoxService<out T> {
bool ShowDialog();
T Result { get; }
}
Why does the following code work:
public class StringInputBoxService : IInputBoxService<string> {
...
}
...
IInputBoxService<object> service = new StringInputBoxService();
and this doesn’t?:
public class IntegerInputBoxService : IInputBoxService<int> {
...
}
...
IInputBoxService<object> service = new IntegerInputBoxService();
Does it have anything to do with int being a value type? If yes, how can I circumvent this situation?
Thanks
Yes, it absolutely has to do with
intbeing a value type. Generic variance in C# 4 only works with reference types. This is primarily because references always have the same representation: a reference is just a reference, so the CLR can use the same bits for something it knows is a string reference as for an object reference. The CLR can make sure that the code will be safe, and use native code which only knows aboutIInputBoxService<object>when passed anIInputBoxService<string>– the value returned fromResultwill be representationally compatible (if such a term exists!).With
int=>objectthere would have to be boxing etc, so you don’t end up with the same code – that basically messes up variance.EDIT: The C# 4.0 spec says this in section 13.1.3.2:
This doesn’t make it terribly obvious, but basically reference conversions only exist between reference types, which leaves only identity conversions (i.e. from a type to itself).
As for workarounds: I think you’d have to create your own wrapper class, basically. This can be as simple as:
It’s pretty nasty though 🙁