[c#] Better way to convert an int to a boolean

The input int value only consist out of 1 or 0. I can solve the problem by writing a if else statement.

Isn't there a way to cast the int into a boolean?

This question is related to c# boolean int

The answer is

int i = 0;
bool b = Convert.ToBoolean(i);

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
        throw new InvalidOperationException("Integer value is not valid");

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

Questions with c# tag:

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 How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .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 Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with boolean tag:

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas How to create a numpy array of all True or all False? Boolean operators ( &&, -a, ||, -o ) in Bash bash "if [ false ];" returns true instead of false -- why? Wait until boolean value changes it state Best approach to converting Boolean object to string in java How to parse JSON boolean value? How to convert a boolean array to an int array What is the printf format specifier for bool? python how to "negate" value : if true return false, if false return true C++ printing boolean, what is displayed? Java check if boolean is null What value could I insert into a bit type column? mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in How to use this boolean in an if statement? Better way to convert an int to a boolean Parsing boolean values with argparse How to return a boolean method in java? What is the correct way to declare a boolean variable in Java? Counting the number of True Booleans in a Python List How to set python variables to true or false? if (boolean == false) vs. if (!boolean) How to toggle a boolean? Get random boolean in Java When should null values of Boolean be used? BOOLEAN or TINYINT confusion True/False vs 0/1 in MySQL How do I concatenate a boolean to a string in Python? Return Boolean Value on SQL Select Statement How do I print out the value of this boolean? (Java) How to count the number of true elements in a NumPy bool array What is the most elegant way to check if all values in a boolean array are true? Convert boolean result into number/integer In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself? How to convert string to boolean php SQL Server - boolean literal? How do I get the opposite (negation) of a Boolean in Python? Default value of 'boolean' and 'Boolean' in Java Which header file do you include to use bool type in c in linux? What evaluates to True/False in R? What is the difference between & and && in Java?

Questions with int tag:

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift Difference between int and double Function stoi not declared How to convert ‘false’ to 0 and ‘true’ to 1 in Python How can I read inputs as numbers? Unsupported operand type(s) for +: 'int' and 'str' How to set null value to int in c#? "int cannot be dereferenced" in Java Python sum() function with list parameter Javascript String to int conversion How can I prevent java.lang.NumberFormatException: For input string: "N/A"? Convert int to char in java Converting a column within pandas dataframe from int to string %i or %d to print integer in C using printf()? casting int to char using C++ style casting How to convert QString to int? How to convert float value to integer in php? How can I write these variables into one line of code in C#? Better way to convert an int to a boolean Converting EditText to int? (Android) Difference between int32, int, int32_t, int8 and int8_t How to check if an int is a null TypeError: Can't convert 'int' object to str implicitly Java : Sort integer array without using Arrays.sort() How to convert int to float in C? C char* to int conversion python int( ) function Java, Simplified check if int array contains int How to convert NUM to INT in R? Is the size of C "int" 2 bytes or 4 bytes? Converting a double to an int in C# Convert char array to a int number in C Convert hex string (char []) to int? How to convert an int value to string in Go? Int to Decimal Conversion - Insert decimal point at specified location int main() vs void main() in C How do I limit the number of decimals printed for a double? What is the difference between Integer and int in Java? Converting a double to an int in Javascript without rounding Splitting String and put it on int array Convert unsigned int to signed int C