Hi Guys,
Here is the problem I am having, I have a class that I want to use to store "properties" for another class, these properties simply have a name and a value. Ideally, what I would like is to be able to add typed properties, so that the "value" returned is always of the type that I want it to be.
The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).
So, I have created a class which is (roughly) this:
public class TypedProperty<DataType> : Property
{
public DataType TypedValue
{
get { // Having problems here! }
set { base.Value = value.ToString();}
}
}
So the question is:
Is there a "generic" way to convert from string back to a primitive?
I can't seem to find any generic interface that links the conversion across the board (something like ITryParsable would have been ideal!).
Update:
@lubos hasko - You understood very well! Your code seems to work like a charm. I can access both the base .Value property (which returns the string) and the subclasses .TypedValue property which always returns the type specified in DataType - Very many thanks, answer accepted!
@Jon Limjap - Thanks for the suggestion, while this would have worked, the problem is that you would still lose the "hard" type of it (i.e. bool, int, whatever) since the return type would become IConvertibleFromString which sadly won't tie in with my original goal.
@dbkk - I have not tried your solution since lubos' worked so well, however I did have concerns about the speed of it (due to reflection) although I am not sure on the actual impact of it. Thank you for the input though.