Assigning type at runtime
c#, reflection
Solution
you can use `Convert.ChangeType` method.
This will cover all base types conversion.
Example : `var i = Convert.ChangeType("1", typeof(int));`
You can also take a look at the `IConvertible` interface 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 :
public static class ConvertUtility
{
public static T Convert<T>(object source) where T : IConvertible
{
return (T)System.Convert.ChangeType(source, typeof(T));
}
}
Problem
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!