Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method and converting: how to define that Type 1 is convertible to Type 2

Tags:

c#

.net

generics

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)

like image 956
Jerry Switalski Avatar asked Feb 13 '17 14:02

Jerry Switalski


People also ask

How do you find the type of generic type?

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.

Is it possible to inherit from a generic type?

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.

How generics works in Java?

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.

What is t in generics Java?

< 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.


1 Answers

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;
}
like image 68
Maksim Simkin Avatar answered Oct 13 '22 00:10

Maksim Simkin