I want to store a list of objects, lets say of type Car, but with an additional 'tag' property eg a boolean True/False which does not belong on the Car class. What is the best way to accomplish this? I need to pass the result between methods.
+2
A:
You could use a tuple of some sort, like Pair<T,U>
.
Heres an exemple:
namespace TestProject.Utils
{
public class Pair<T, U>
{
public Pair(T first, U second)
{
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
}
}
For C#4, here's a good read about tuple : CLR Inside Out - Building Tuple
EDIT : Usage
Car mustang;
List<Pair<Car, bool>> list = new List<Pair<Car, bool>>(); // <Car, isAwesome> pairs..
list.Add(new Pair(mustang, true));
Dynami Le Savard
2010-04-08 17:42:43
This is a good idea, but...if I'm retrieving the list of cars then want to append the tag afterwards, I'll have to convert objects from one kind of list to another. And I already have to do this again later. Is it bad practice to be converting lists or this a common scenario?
MC.
2010-04-08 18:03:54
A:
Dictionary<Car, bool> carFlags = new Dictionary<Car, bool>();
You can pass the car into the dictionary and get back the bool flag.
gbogumil
2010-04-08 17:48:01
A:
Using inheritance, you can create a CarWithTag class that extends the Car class without polluting the Car class with unneeded properties:
public class Car
{
public string CarInfoEtcetera { get; set; }
}
public class CarWithTag : Car
{
public string Tag { get; set; }
}
Then you can create a method that accepts a CarWithTag object when you need to pass tag info as well.
private string GetCarTagInfo(CarWithTag car)
{
return car.Tag;
}
Now you can new up a CarWithTag object and pass it into the method, along with any Car info.
CarWithTag carWithTag = new CarWithTag()
{
Tag = "123abc",
CarInfoEtcetera = "etc"
};
string tag = GetCarTagInfo(carWithTag);
DShultz
2010-04-08 18:02:48