views:

297

answers:

3

I have a method which is connecting to a database via Odbc. The stored procedure which I'm calling has a return value which from the database side is a 'Char'. Right now I'm grabbing that return value as a string and using it in a simple if statement. I really don't like the idea of comparing a string like this when only two values can come back from the database, 0 and 1.

OdbcCommand fetchCommand = new OdbcCommand(storedProc, conn);
fetchCommand.CommandType = CommandType.StoredProcedure;
fetchCommand.Parameters.AddWithValue("@column ", myCustomParameter);
fetchCommand.Parameters.Add("@myReturnValue", OdbcType.Char, 1).
   Direction = ParameterDirection.Output;
fetchCommand.ExecuteNonQuery();
string returnValue = fetchCommand.Parameters["@myReturnValue"].Value.ToString();
if (returnValue == "1")
{
     return true;
} 

What would be the proper way to handle this situation. I've tried 'Convert.ToBoolean()' which seemed like the obvious answer but I ran into the 'String was not recognized as a valid Boolean. ' exception being thrown. Am I missing something here, or is there another way to make '1' and '0' act like true and false?

Thanks!

+13  A: 

How about:

return (returnValue == "1");

or as suggested below:

return (returnValue != "0");

The correct one will depend on what you are looking for as a success result.

Kevin
Correct? Check; Concise? Check; Elegant? Check. +1.
Earlz
I would recommend using `return (returnValue!="0")`. It would be more natural that `0` is `false` and every number that is not zero is `true`. Of course here we have the case where Chris uses strings instead of numbers, so this comment is only partly valid ;)
Gacek
It's always a debate. 0 also mean ERROR_SUCCESS which mean that everything went well. But I agree with Gacek that it is more natural.
Pierre-Alain Vigeant
Nice and concise.
Chris
A: 

Set return type to numeric - you don't need a char (so don't use it); a numeric value (0/1) can be converted with Convert.ToBoolean(num)

Otherwise: use Kevin's answer

riffnl
I wish that we could change the return type. But we're stuck with what it is.
Chris
+2  A: 

If you want the conversion to always succeed, probably the best way to convert the string would be to consider "1" as true and anything else as false (as Kevin does). If you wanted the conversion to fail if anything other than "1" or "0" is returned, then the following would suffice (you could put it in a helper method):

if (returnValue == "1")
{
    return true;
}
else if (returnValue == "0")
{
    return false;
}
else
{
    throw new FormatException("The string is not a recognized as a valid boolean value.");
}
Zach Johnson
Nice idea to catch the unrecognized value. Not sure I want to go that way, but still a good idea.
Chris