C# Convert ToBoolean(Object)

Description

Convert ToBoolean(Object) converts the value of a specified object to an equivalent Boolean value.

Syntax

Convert.ToBoolean(Object) has the following syntax.


public static bool ToBoolean(
  Object value
)

Parameters

Convert.ToBoolean(Object) has the following parameters.

  • value - An object that implements the IConvertible interface, or null.

Returns

Convert.ToBoolean(Object) method returns true or false, which reflects the value returned by invoking the IConvertible.ToBoolean method for the underlying type of value. If value is null, the method returns false.

Example

The following example converts an array of object values to Boolean values.


/*w w  w  .  j av  a2 s .  c o  m*/
using System;
public class MainClass{
  public static void Main(String[] argv){  
    object[] objects = { 1.33, -2, 0, "1", "1.7", String.Empty, 
                         "1Sasdftring", "True", "false", null, 
                         new System.Collections.ArrayList() };
    
    foreach (object obj in objects)
    {
       Console.Write("{0,-40}  -->  ", 
                     obj != null ? 
                     String.Format("{0} ({1})", obj, obj.GetType().Name) : 
                     "null");
       try {
          Console.WriteLine("{0}", Convert.ToBoolean(obj));
       }   
       catch (FormatException) {
          Console.WriteLine("Bad Format");
       }   
       catch (InvalidCastException) {
          Console.WriteLine("No Conversion");
       }   
    }     

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version