This class has the responsibility of parsing a string to one of the primitive types: int
, double
, float
, decimal
...
While creating it, I have noticed that it'll be terribly ugly.
It basically should perform a TryParse
of each primitive type and return the first that returns true, along with the parsed value.
public static class PrimitiveParser
{
public static bool TryParse(Type targetType, string sourceValue, out object result)
{
result = null;
if (targetType == typeof(int))
{
int intResult;
var parseResult = int.TryParse(sourceValue, out intResult);
{
result = intResult;
return parseResult;
}
}
if (targetType == typeof(double))
{
double doubleResult;
var parseResult = double.TryParse(sourceValue, out doubleResult);
{
result = doubleResult;
return parseResult;
}
}
if (targetType == typeof(float))
{
float floatResult;
var parseResult = float.TryParse(sourceValue, out floatResult);
{
result = floatResult;
return parseResult;
}
}
/// ...
return false;
}
}