Say I have the following class:
public class MyClass<T>
{
public MyClass() {
//construct logic
}
public IProperty<T> MyProperty { get; set; }
}
public interface IProperty<T> { }
public DateTimeProperty : IProperty<DateTime>
{
}
If I try to put this code into the constructor of MyClass:
if (typeof(T) == typeof(DateTime))
MyProperty = new DateTimeProperty();
I get the following compilation error:
Cannot implicitly convert type ‘DateTimeProperty’ to ‘IProperty’
How can I, in the constructor of MyClass, set the value of MyProperty to be a new DateTimeProperty, only if T is of type DateTime?
Note that generics should really be exactly that; generic; what you are doing is specialized (for some
T), which is kinda not the point. However, as for how – cast:By casting to
objectand then back up to(IProperty<T>)you remove the compiler’s ability to apply static type-checking rules. And the downside: you remove the compiler’s ability to apply static type-checking rules.