I have entity class generated by E-R designer that I have modified a little. This is declaration:
public abstract partial class Preference<T> : EntityObject, IPreference<T>
Then there is another entity class declared as follows:
public partial class BoolPref : Preference<bool>
so BoolPref inherits from Preferences<bool>.
Now I have this generated property:
public ObjectSet<Preference<object>> Preferences
{
get
{
if ((_Preferences == null))
{
_Preferences = base.CreateObjectSet<Preference<object>>("Preferences");
}
return _Preferences;
}
}
private ObjectSet<Preference<object>> _Preferences;
When I try to add new BoolPref to this ObjectSet as follows
context.Preferences.AddObject(new BoolPref ());
I get compile time error.
How can I add instances of BoolPref to Preferences ? Where is the mystake ?
Suppose
Preference<T>has a read-write property called Value of type T. Now suppose the type system works the way you’d like it to:That’s legal at compile time because set.First().Value has compile time type of object, not bool. But at runtime it is of type bool, and you just called a setter that takes a bool and passed a string, corrupting memory in the CLR which then crashes and dies horribly.
That’s why this is not legal. In C# 4 you can have generic covariance and contravariance only if it is provably typesafe, and only if the generic type is an interface or delegate, and only if the varying type argument is of reference type.