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#.
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
}
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With