Convert string to Boolean in CSharp

Description

The following code shows how to convert string to Boolean.

Example


using System;/*from  w w w.java 2  s.  c o m*/

public class MainClass
{
   public static void Main()
   {
      ConvertToBoolean(null);
      ConvertToBoolean(String.Empty);
      ConvertToBoolean("true");
      ConvertToBoolean("TrueString");
      ConvertToBoolean("False");
      ConvertToBoolean("    false    ");
      ConvertToBoolean("-1");
      ConvertToBoolean("0");
   }

   private static void ConvertToBoolean(string value)
   {
      try
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, Convert.ToBoolean(value));
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}' to a Boolean.", value);
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var