c# - Cast expression failure on Generic -
apologize in advance, such trivial question confused
i have class hierarchy follows
namespace mynamespace { public class classa {} public class typea<a> : classa { public p1 { get; set; } } public class subtypea<a> : typea<a> : classa { public typea<a> p2 { get; set; } public void foo() { var x = new typea<classa>(); var y = (typea<classa>) p2; } } }
why can't c# cast p2
typea<classa>
while p2
instance of typea<a>
a
of type classa
?
thanks
you're looking covariance , isn't supported on classes, in interfaces , delegates.
design interface follows:
public interface itypea<out a> : classa { p1 { get; } } public class classa { } public class typea<a> : itypea<a> : classa { public p1 { get; set; } } public class subtypea<a> : typea<a> : classa { public typea<a> p2 { get; set; } public void foo() { var x = new typea<classa>(); itypea<classa> y = p2; } }
the drawback here property of covariant generic type isn't valid if can set.
type inference madness
i want suggest you shouldn't use type inference on explicit typing everywhere.
see following sentence in question:
var y = (typea<classa>)p2;
if able whole cast (as test isn't possible without covariance), you're using explicit cast provide type of variable, while same can better expressed follows:
// implicit cast typea<classa> y = p2;
implicit typing/type inference isn't more readable , shouldn't used specify type, because c# can explicitly define type given reference declaration...
that's reason behind answer doesn't use explicit cast:
itypea<classa> y = p2;
Comments
Post a Comment