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.
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.
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.
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.
public static List<T> CreateCompatibleList<T> (T t)
{
return new List<T> () ;
}
var x = 10 ;
var l = CreateCompatibleList (x) ;
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.
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