Question :
Generic type conversion FROM string,
Answer :
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 : 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!).
,
I am not sure whether I understood your intentions correctly, but let’s see if this one helps.
public class TypedProperty : Property where T : IConvertible { public T TypedValue { get { return (T)Convert.ChangeType(base.Value, typeof(T)); } set { base.Value = value.ToString();} } }
That’s the answer Generic type conversion FROM string, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.
Disclaimer :
The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you