Click to See Complete Forum and Search --> : [2.0] Dynamic Generic List<T>
vbud
May 10th, 2007, 06:17 AM
Hi all,
I have a situation such that it is only at run time that i would know what type of generic list i want to create. Therefore I need something like:
Private List<IBase> Test(IBase myObj) // where IBase is a base class which all others inherit
{
Type myType = GetType(myObj)
Return new List<myType>;
}
I know the code above is rubbish, its just to give you an idea of what i want to achieve. Any ideas???
penagate
May 10th, 2007, 06:58 AM
Bit hard to make a suggestion without knowing a bit more about the particulars of the situation, but what you could do is make a static function in each class that inherits from IBase (side note: the I- prefix usually denotes an interface, not an abstract class; consider changing this to avoid confusion) that returns a vector of that particular type.
However, you should bear in mind that if you are only ever going to call members of IBase upon the elements contained in the list(s), then you stand to gain no benefit by using a more specific type than List<IBase>.
vbud
May 10th, 2007, 07:16 AM
Ok, here goes:
IBase in an Interface Class defining methods and properties that all classes implements.
BaseClass is a generic class that implements IBase
Within BaseClass there's a method that looks like:
public List<IBase> GetList(IBase obj)
{
//
}
ClassA, ClassB, ClassC etc inherits BaseClass
Basically in the above, obj can be ClassA, ClassB or ClassC, etc...
The idea is to have pass the appropriate class as parameter to the above method and it would in turn return a generic list of that class.
mendhak
May 10th, 2007, 02:19 PM
Like this?
public static List<T> GetList<T>(int size)
{
return new List<T>(size);
}
jmcilhinney
May 15th, 2007, 05:03 AM
What mendhak suggests will go part of the way but there's no way to limit what T can be, so that GetList method cannot be limited to returning Lists of types that implement IBase. Also, you couldn't do this:List<IBase> list = GetList<ClassA>(100);because List<IBase> and List<ClassA> are different classes. Even though one type of item may inherit or implement the other, that doesn't mean that the collections themselves inplement or inherit each other.
vbud
May 17th, 2007, 04:58 AM
Ok thats my point, so you can't return a list of say ClassA as being same as a List of IBASE. I'll have to find another way then...
jmcilhinney
May 17th, 2007, 05:21 AM
Generics make many situations easier that were tedious in .NET 1.x, but there are certain things that can't, and shouldn't, be possible. You'd basically have to break typing rules to achieve your aim. If you don't know the types of things until run time then the solution is reflection. It's tedious to do anything of any complexity but you can do anything you want without knowing the actual types until run time.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.