Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?
Type k = typeof(double); List<k> lst = new List<k>();
Yes, this is nice especially if the generic class is abstract, you can do this in the concrete subclasses :) @TimKuipers The <E> in class Foo<E> is not bound to any particular type.
A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.
Yes, there is:
var genericListType = typeof(List<>); var specificListType = genericListType.MakeGenericType(typeof(double)); var list = Activator.CreateInstance(specificListType);
A cleaner way might be to use a generic method. Do something like this:
static void AddType<T>() where T : DataObject { Indexes.Add(typeof(T), new Dictionary<int, T>()); }
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