Collection of objects
-
Hi guys, I have a class named Configuration which is basically a collection of configItems. Each config item has the following: ID (allows persisting to file/database) Name (a friendly way of searching for the item) Value (self explanatory) At present, ID is an integer type and both Name and Value members are string types. However, the value may actually represent a boolean, integer, string, decimal and potentially other types. The annoyance is currently having to cast the value to and from string to whaterver object type is required. It would be great if the Value member could be the correct object type without having to cast each time. I guess being able to have a generic member would be ideal but from my knowledge of generics, this doesn't appear possible. How do you guys approach situations like this? What would you do?
Regards Wayne Phipps ____________ Time is the greatest teacher... unfortunately, it kills all of its students View my Blog
-
Hi guys, I have a class named Configuration which is basically a collection of configItems. Each config item has the following: ID (allows persisting to file/database) Name (a friendly way of searching for the item) Value (self explanatory) At present, ID is an integer type and both Name and Value members are string types. However, the value may actually represent a boolean, integer, string, decimal and potentially other types. The annoyance is currently having to cast the value to and from string to whaterver object type is required. It would be great if the Value member could be the correct object type without having to cast each time. I guess being able to have a generic member would be ideal but from my knowledge of generics, this doesn't appear possible. How do you guys approach situations like this? What would you do?
Regards Wayne Phipps ____________ Time is the greatest teacher... unfortunately, it kills all of its students View my Blog
You could create a base class that contains just Id and Name, and create subclasses for each data type. The base class could contain methods for getting data from each subclass. For example:
public int GetInt32() {
ConfigurationItemInt32 item = this as ConfigurationItemInt32;
if (item == null) {
throw new ApplicationException("Item is not an Int32 value.");
}
return item.Value;
}--- single minded; short sighted; long gone;