Is it possible to declare an instance of a generic without knowing the type at design-time?
Example:
Int i = 1; List<typeof(i)> list = new List<typeof(i)>();
where the type of i could be anything, instead of having to do:
List<int> list = new List<int();
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
Constructing an Instance of a Generic TypeYou cannot create instances of it unless you specify real types for its generic type parameters.
Extension Methods is a new feature in C# 3.0 and the Common Language Runtime, which allows existing classes to use extra methods (extension methods) without being implemented in the same class or obtained by inheritance.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
If you don't know the type at compile-time, but you want the actual type (i.e. not List<object>
) and you're not in a generic method/type with the appropriate type parameter, then you have to use reflection.
To make the reflection simpler, I've sometimes introduced a new generic type or method in my own code, so I can call that by reflection but then just use normal generics after that. For example:
object x = GetObjectFromSomewhere(); // I want to create a List<?> containing the existing // object, but strongly typed to the "right" type depending // on the type of the value of x MethodInfo method = GetType().GetMethod("BuildListHelper"); method = method.MakeGenericMethod(new Type[] { x.GetType() }); object list = method.Invoke(this, new object[] { x }); // Later public IList<T> BuildListHelper<T>(T item) { List<T> list = new List<T>(); list.Add(item); return list; }
Of course, you can't do an awful lot with the list afterwards if you don't know the type... that's why this kind of thing often falls down. Not always though - I've used something like the above on a few occasions, where the type system just doesn't quite let me express everything I need to statically.
EDIT: Note that although I'm calling Type.GetMethod in the code above, if you were going to execute it a lot you'd probably want to just call it once - after all, the method isn't going to change. You may be able to make it static (you could in the case above) and you probably want to make it private too. I left it as a public instance method for the simplicity of the GetMethod call in sample code - you'd need to specify the appropriate binding flags otherwise.
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