I defined this method:
public static List<T2> ConvertList<T1, T2>(List<T1> param) where T1:class where T2:class
{
List<T2> result = new List<T2>();
foreach (T1 p in param)
result.Add((T2)p);
return result;
}
For converting Lists of Type 1 to Lists of Type 2.
Unfortunately I forgot, that C# compiler cannot say at this stage that T1
is convertible to T2
, so it throws error:
error CS0030: Cannot convert type T1 to T2
Can someone direct me how to do it properly? I need this method for now only to convert list of custom class to list of object
, so as in .NET everything derives from object
it should work.
Basically what I would expect is some syntax to tell compiler that T2 (object
) is base for T1 (MyClass
), so something like:
public static List<T2> ConvertList<T1, T2>(List<T1> param) where T2: base of T1
(... where T2: base of T1)
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.
Java generics are implemented through type erasure, i.e. type arguments are only used for compilation and linking, but erased for execution. That is, there is no 1:1 correspondence between compile time types and runtime types.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
You could specify it in a generic parameter:
public static List<T2> ConvertList<T1, T2>(List<T1> param)
where T1:class,T2
where T2:class
{
List<T2> result = new List<T2>();
foreach (T1 p in param)
result.Add((T2)p);
return result;
}
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