Question

I may have the following types:
Number with decimal : 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.

Was it helpful?

Solution

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 ints can always be parsed as decimal. You may want to re-order the TryParses to put the int one first.

OTHER TIPS

TryParse() is your friend, however I don't understand what you want as all valid ints are also valid decimals.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top