[c#] How to convert "0" and "1" to false and true

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!

This question is related to c# .net asp.net odbc boolean-logic

The answer is


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


In a single line of code:

bool bVal = Convert.ToBoolean(Convert.ToInt16(returnValue))

Or if the Boolean value is not been returned, you can do something like this:

bool boolValue = (returnValue == "1");

You can use that form:

return returnValue.Equals("1") ? true : false;

Or more simply (thanks to Jurijs Kastanovs):

return returnValue.Equals("1");

My solution (vb.net):

Private Function ConvertToBoolean(p1 As Object) As Boolean
    If p1 Is Nothing Then Return False
    If IsDBNull(p1) Then Return False
    If p1.ToString = "1" Then Return True
    If p1.ToString.ToLower = "true" Then Return True
    Return False
End Function

(returnValue != "1" ? false : true);

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.");
}

If you don't want to convert.Just use;

 bool _status = status == "1" ? true : false;

Perhaps you will return the values as you want.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to odbc

How to connect PHP with Microsoft Access database [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified Does MS Access support "CASE WHEN" clause if connect with ODBC? The specified DSN contains an architecture mismatch between the Driver and Application. JAVA Setting up PostgreSQL ODBC on Windows How to search for rows containing a substring? Simplest Way to Test ODBC on WIndows How to convert "0" and "1" to false and true Excel: Use a cell value as a parameter for a SQL query How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Examples related to boolean-logic

pandas: multiple conditions while indexing data frame - unexpected behavior How can I obtain the element-wise logical NOT of a pandas Series? How to test multiple variables against a value? Any good boolean expression simplifiers out there? if (boolean == false) vs. if (!boolean) How do I test if a variable does not equal either of two values? Differences in boolean operators: & vs && and | vs || Check if at least two out of three booleans are true How to convert "0" and "1" to false and true Does Python support short-circuiting?