Cascading parse
I may have the following types:
Number with decimal开发者_如何学C : 100.90 Number (int32) : 32 String : ""What I want is a function which tries to parse as a decimal and if it fails, then tries to parse as an int and if that fails then its a string. Any sort of function in C# which has the following functionality is appreciated.
public static object cascadeParse(string obj)
{
decimal decRet;
if (!decimal.TryParse(obj, out decRet))
{
int intRet;
if (!int.TryParse(obj, out intRet))
{
return obj;
}
else
{
return intRet;
}
}
else
{
return decRet;
}
}
However this method will always return a decimal
when passed something that can be parsed as an int
as int
s can always be parsed as decimal
. You may want to re-order the TryParse
s to put the int
one first.
TryParse() is your friend, however I don't understand what you want as all valid ints are also valid decimals.
精彩评论