Reputation: 4944
I'm trying to check if a given object implements an interface I made that takes a generic parameter.
public interface ICaseCopier<T> where T : ModelElement
{
T Case1 { get; set; }
T Case2 { get; set; }
void CopyCase(T caseToCopy, T copiedCase);
}
One of my objects implements the interface like this:
public class ProcessLoad : ElectricalLoad, ICaseCopier<ProcessCase>
Where ProcessCase is a child of ModelElement. I have many objects that use that interface with different parameters in the generic, so checking them one by one is out of the question.
What I tried is this:
ICaseCopier<ModelElement> copier = this as ICaseCopier<ProcessCase>;
But I get the following error:
Cannot convert source type 'ICaseCopier<ProcessCase>' to target type 'ICaseCopier<ModelElement>'
ProcessCase is castable to ModelElement.
Upvotes: 0
Views: 134
Reputation: 144206
You can't do this since the conversion isn't safe - if it were you could do the following:
public class OtherElement : ModelElement { }
ICaseCopier<ModelElement> copier = this as ICaseCopier<ProcessCase>;
copier.Case1 = new OtherElement();
The only way you can do this is to make the ICaseCopier<T>
interface covariant, which you can't do in its current form since T
appears in both input and output positions.
Upvotes: 5