Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a double or string for a method

Tags:

c#

generics

I have a method:

public static double c(string val)
{
    return Math.Round(Convert.ToDouble(val), 4);
}

Where I pass in a string, and if its a double, I want to round then return a double, but if its a string, I want to return a string as is. All of the parameters that I pass in will be strings to start, how do i determine if its a string or double, and how do i rewrite the methoed to have the return type flexible enough to return either?

Ideally, I would like to use type variant like in vba, but i dont think there is an analog in c#.

like image 706
greg Avatar asked Aug 06 '26 07:08

greg


2 Answers

The following will try to parse the double. If returns true it will put the double in the output variable output; else return false means val isn't a double and you should use the string val instead.

public static bool c(string val, out double output)
{
    if (double.TryParse(val, out output))
    {
        output = Math.Round(output, 4);
        return true;
    }
    else
    {
        output = 0;
        return false;
    }
}

Use like this:

string val = "123.45678";
double output;
if ( c(val, out output) )
{
    // use double output
}
else
{
    // val isn't a double, just use val directly
}
like image 159
Chris Snowden Avatar answered Aug 07 '26 21:08

Chris Snowden


You can use typeof() and set your parameter of the function to object. Then you can pass everything to the function and can check the type with typeof().

like image 45
Aykut Çevik Avatar answered Aug 07 '26 19:08

Aykut Çevik