PDA

Click to See Complete Forum and Search --> : Some help Generics


Rauland
Jun 1st, 2007, 04:19 PM
Hi,

Lets say I have a function,which accepts as a parameter a string.

Depending on the value of this string I would like to return a generic list of different types.

So, for instance:

Lets say I pass in the word,"dogs", well then Iīd like to return List<Dogs> mydogList = new List<Dogs>();

If I pass in the word "cars", well the same thing,return List<Cars> myCarlist = new List<Cars>();

My function I had in mind would be something similiar to:
(Please note that the code below is incorrect!)


Public List<T> MyFunction(String str)
{
switch (str)
case "Dogs":
return List<dogs> dogsList = new list<dogs>();
Case "Cars":
return List<cars> carList = new list<cars>();
}

But this obviously doesnīt work,...

Could sb please shine some light on how to improve my approach, or take a totally different one?
Thanks !

jmcilhinney
Jun 1st, 2007, 08:16 PM
You cannot do what you want by passing a string. You could do it by passing an instance of the type you wanted to make the list items, e.g.private void Form1_Load(object sender, EventArgs e)
{
List<int> integers = this.CreateList(0);

List<string> strings = this.CreateList("");
}

public List<T> CreateList<T>(T type)
{
return new List<T>();
}If you do it the way you are currently you would have to add a case for every type you wanted to support. In that case your cases should look like this:case "String"
return new List<string>();

Rauland
Jun 2nd, 2007, 01:11 PM
Hi Thanks,

I eventualy opted for an easier approach sth like:


List<dog> dogs;
List<car> cars;

private void LoadList(string str)
{
switch(str)
{
case dog:
dogs = new List<dog>();
dogs.add(new dog("jimmy"));
break;
case car:
cars = new List<car>()
,....
,..
}
}
}

It would be great though to somehow combine your code with this approach;

Sth like:

Private List<T> LoadList<T>(T type)
{
Problem (1)
switch(type.GetType())
{
case dog.GetType():
List<T> dogList = new List<T>();
problem(2)("Would like to add dog items")
return dogList;


case car.GetType():
break;
}


But, run into problems.
1) First I find I canīt do a Switch based on a variableīs type.
2) I can only return an empty List<T>. So if the type is "Car", I will only be able to return an empty,List<Car>, I mean by empty, with no Car items.
I canīt add Car items to the list from within the switch, as I would need Car objects, and I canīt add them to a List<T> type.

Maybe I am over complicating things, but just would like to learn how to do things in a different way,..
Thanks!:o

jmcilhinney
Jun 2nd, 2007, 08:41 PM
You're trying to do things in a way that they were never intended. You would have to look into reflection.