How to convert "0" and "1" to false and true

Chris picture Chris · Apr 15, 2010 · Viewed 175.9k times · Source

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!

Answer

kemiller2002 picture kemiller2002 · Apr 15, 2010

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.