Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic types with type parameter in C#

I don't think that this could be done in C#, but posting this just to make sure. Here's my problem. I would like to do something like this in C#:

var x = 10;
var l = new List<typeof(x)>();

or

var x = 10;
var t = typeof(x);
var l = new List<t>();

But of course this doesn't work. Although this shouldn't be a problem as the type t is resolved at compile time. I understand that this can be solved with reflection, but as types are known at compile time using reflection would be overkill.

like image 676
Max Avatar asked Aug 31 '09 17:08

Max


People also ask

What is type parameters in generics?

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.

How many type parameters can be used in a generic class?

You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

What is generic class explain it with bounded type parameter?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.


2 Answers

public static List<T> CreateCompatibleList<T> (T t)
{
    return new List<T> () ;
}

var x = 10 ;
var l = CreateCompatibleList (x) ;
like image 162
Anton Tykhyy Avatar answered Sep 20 '22 14:09

Anton Tykhyy


You're trying to get .Net to set a generic type using a run-time operator. As you know, that won't work. Generics types must be set at compile time.

like image 44
Joel Coehoorn Avatar answered Sep 21 '22 14:09

Joel Coehoorn