Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upcasting with a generic type parameter

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.

like image 213
Auraseer Avatar asked Feb 09 '10 18:02

Auraseer


People also ask

What is a generic type parameter?

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.

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

What is generic parameter in C#?

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.


1 Answers

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.

like image 148
Bryan Watts Avatar answered Oct 17 '22 13:10

Bryan Watts