c# casting to and from interface types with generic types -
i have class mockrepository
implements interface irepository
, have class technology
implements interface iidentifiable
.
i want cast object mockrepository<technology>
irepository<iidentifiable>
, cast again after operations complete. possible? code compiles when try run invalid cast exception.
short answer no.
if have interface imyinterface<t>
compiler create new interface each type of t use , substitute values of t.
to give example:
i have interface:
public interface imyinterface<t> { public t value {get; set;} }
i have 2 classes:
public class foo {} public class bar : foo {}
i define following
public class orange : imyinterface<foo> {} public class banana : imyinterface<bar> {}
the compiler automatically create 2 new interfaces using specific name convention, i'm going use different names highlight different
public interface randominterface { foo value { get; set; } } public interface alternativeinterface { bar value { get; set; } } public class orange : randominterface { } public class banana : alternativeinterface { }
as can see there no relationship between randominterface
, alternativeinterface
. class inheriting randominterface
cannot cast alternativeinterface
update after reading question comments
if wish pass mockrepository function expects irepository can following
public void myfunction<t>(irepository<t> repo) t: iidentifiable { }
Comments
Post a Comment