I have a variable x of type T and value that is in a string.
For example I have:
bool x, value = "True"
int x, value = "1"
- Is there a generic way to assign/parse/deserialize the value to x?
Note that T may be referenced or primitive type!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
you can use
Convert.ChangeTypemethod.This will cover all base types conversion.
Example :
var i = Convert.ChangeType("1", typeof(int));You can also take a look at the
IConvertibleinterface that you can use for converting your own objects from or to another type.Finally, as codymanix said, you can rely on the OOB XmlSerialization or Binary Serialization to serialize your objects.
[edit] you can check at compile time if the target type is convertible by wrapping the convert.ChangeType method in an utility class like this :