C # does not allow implicit string conversion to Boolean, since the Boolean variable can only have the values True or False and the string can have millions of different characters.
I suppose that the string you want to convert to a boolean contains: "True" or "False", so, to evaluate if the string can be converted to a boolean, you must use the static method tryParse implemented by all primitive data types .
for example:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
const string miValorVerdero = "True";
const string miValorFalso = "False";
const string miNombre = "Juan";
if (bool.TryParse(miValorVerdero, out var miVariableBooleana))
{
Console.WriteLine("Se puede convertir miValorVerdero");
Console.WriteLine($"el valor de miVariableBooleana es: {miVariableBooleana}");
}
else
{
Console.WriteLine("NO Se pudo convertir miValorVerdero");
}
if (bool.TryParse(miValorFalso, out miVariableBooleana))
{
Console.WriteLine("Se pudo convertir miValorFalso");
Console.WriteLine($"el valor de miVariableBooleana: {miVariableBooleana}");
}
else
{
Console.WriteLine("NO Se pudo convertir miValorFalso");
}
if (bool.TryParse(miNombre, out miVariableBooleana))
{
Console.WriteLine("Se pudo convertir miNombre");
Console.WriteLine($"el valor de miVariableBooleana: {miVariableBooleana}");
}
else
{
Console.WriteLine("NO se pudo convertir miNombre");
}
Console.Read();
}
}
}
// Output:
// Se puede convertir miValorVerdero
// el valor de miVariableBooleana es: True
// Se pudo convertir miValorFalso
// el valor de miVariableBooleana: False
// NO se pudo convertir miNombre
You can also develop your own method to determine if a string can be converted to boolean by following your own rules. Ex:
public static bool ConvertirStrBool(string cadena)
{
switch (cadena.ToLower())
{
case "true":
return true;
case "t":
return true;
case "1":
return true;
case "0":
return false;
case "false":
return false;
case "f":
return false;
default:
throw new InvalidCastException("Este valor no se puede convertir a bool!");
}
}