Reputation: 73
I am converting a string to a datatype based on the another string that contains the name of datatype. I have two string like below:
string string_1 = "true";
string string_2 = "System.Boolean";
i need to convert the string 1 to the data type that is specified in string 2. how can i do that?(note that the string_2 can be each datatype) must i use if's for checking string_2 with any type of datatype?
Upvotes: 1
Views: 92
Reputation: 1382
For the given type ChangeType
works well:
Convert.ChangeType(string_1, Type.GetType(string_2))
But if you have different types, like an own class, this won't work. In that case, there is no such generic way, since the framework cannot now how to parse a value. If you try, you will get a InvalidCastException
. In that case, you can only hand-write a converter.
In the special case, you have - beside primitives - only own classes, you could consider using a static-conversion method in each class for the job. Would probably look like this:
Type.GetType(string_2).GetMethod("convert").Invoke(string_1)
Anyway, no nice solution here. IMHO, the hand-written conversion (doing it with ifs) is the only proper way.
Upvotes: 1
Reputation: 49133
Assuming the target type is a primitive that is either Convertible
or Parse
able, you can try the following:
object result;
string string_1 = "true";
string string_2 = "System.Boolean";
var targetType = Type.GetType(string_2);
if (typeof(IConvertible).IsAssignableFrom(targetType))
{
result = Convert.ChangeType(string_1, targetType);
}
else
{
var parseMethod = targetType.GetMethod("Parse", new[] {typeof (string)});
if (parseMethod != null)
result = parseMethod.Invoke(null, new object[] { string_1 });
}
See ChangeType
Upvotes: 1