Is it possible to "upcast" from a generic class based on T, into a generic class based on something more general than T?
For instance, say I have a class named Derived
that inherits from a class named Base
. Can I ever do something like this:
List<Derived> der = new List<Derived>();
List<Base> bas = (List<Base>) der;
Or, using interfaces, is it ever possible to do something like this:
List<MyClonableType> specific = new List<MyClonableType>();
List<IClonable> general = (List<IClonable>)specific;
As written here, each of these examples fails with an InvalidCastException
. The question we're arguing about is whether it's actually impossible, or simply a syntax error that could be fixed if we knew how.
Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
Generic became part of C# with version 2.0 of the language and the CLR, or Common Language Runtime. It has introduced the concept of type parameters, which allow you to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
C# 4.0 will have that feature.
It will be enabled on interfaces and delegates which adhere to certain rules. List<T>
won't be supported, as it is a concrete class. IList<T>
also won't be supported, as its methods use T
in both the in
and out
positions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With