I have two interfaces like the following:
public interface IEntityViewModel<T> : IEntityViewModel where T : class, ICLEntity
{
new T Entity { get; set; }
}
public interface IEntityViewModel
{
void LoadEntity(int primaryKey);
bool? DialogResult { get; set; }
ICLEntity Entity { get; set; }
}
When I implement a class, how can I ensure that the Entity property that appears on the class is the generic T? Here’s a sample class:
public abstract class EntityConductor<T> : IEntityViewModel<T>
where T : class, ICLEntity
{
public T Entity
{
get; set;
}
}
The compiler requires I add the IEntityViewModel implementation as well, for example:
ICLEntity IEntityViewModel.Entity
{
get
{
return ActiveItem.Entity;
}
set
{
ActiveItem.Entity = value as T;
}
}
but then I get two Entity properties in the class, which is not what I need. If implementing the generic interface, I need the Entity property to be of type T, and if the non generic, to be of type ICLEntity.
How can this be done? Am I missing something simple? I am using .NET 4.0, can covariance help me here?
Thanks!
I don’t think this can be done. You pretty much already have the best you can do.
This should ensure that when working with an IEntityViewModel object you can use the strongly typed property, but if you only know it to be an IEntityViewModel object then you will be using the weakly typed property. There is no additional storage requirement so I don’t see the problem with this. This construct reflects what appears to be your usage scenario – you have an object but in some circumstances you may not have the type information to allow use of the strongly typed property.
As a sidenote, the setter in IEntityViewModel.Entity should throw an exception if the parameter is the wrong type.