c cast to boolean code example
Example 1: java cast int to boolean
boolean result = (myBinaryInt == 1);
boolean result2 = (myNonBinaryInt >= 1);
Example 2: c# relaxed boolean cast
public static class BoolParser
{
public static bool GetValue(string value, bool defaultValue)
{
var result = IsTrue(value, defaultValue);
if (result == null) return defaultValue;
return (bool) result;
}
public static bool? GetValue(string value)
{
return IsTrue(value);
}
private static bool? IsTrue(string value, bool? defaultValue = null)
{
try
{
if (value == null)
{
return defaultValue;
}
value = value.Trim().ToLower();
switch (value)
{
case "true":
case "t":
case "1":
case "yes":
case "yeah":
case "yup":
case "y":
return true;
case "false":
case "f":
case "0":
case "no":
case "nope":
case "n":
return false;
default:
return defaultValue;
}
}
catch
{
return defaultValue;
}
}
}