Export (0) Print
Expand All

Convert.ToBoolean Method (Object)

Converts the value of a specified Object to an equivalent Boolean value.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public static bool ToBoolean (
	Object value
)
public static boolean ToBoolean (
	Object value
)
public static function ToBoolean (
	value : Object
) : boolean

Parameters

value

An Object that implements the IConvertible interface or a null reference (Nothing in Visual Basic).

Return Value

false if value equals a null reference (Nothing in Visual Basic). -or- true or false; the result of invoking the IConvertible.ToBoolean method for the underlying type of value.

The following code sample illustrates the use of the ToBoolean method, converting a string value to a Boolean type.

public void ConvertStringBoolean(string stringVal) {
    
    bool boolVal = false;

    try {
        boolVal = System.Convert.ToBoolean(stringVal);
        if (boolVal) {
            System.Console.WriteLine(
                "String was equal to System.Boolean.TrueString.");
        }
        else {
            System.Console.WriteLine(
                "String was equal to System.Boolean.FalseString.");
        }
    }
    catch (System.FormatException){
        System.Console.WriteLine(
            "The string must equal System.Boolean.TrueString " +
            "or System.Boolean.FalseString.");
    }

    // A conversion from bool to string will always succeed.
    stringVal = System.Convert.ToString(boolVal);
    System.Console.WriteLine("{0} as a string is {1}",
        boolVal, stringVal);
}

public void ConvertStringBoolean(String stringVal)
{
    boolean boolVal = false;

    try {        
        boolVal = System.Convert.ToBoolean(stringVal);
        if (boolVal) {            
            System.Console.WriteLine(
                "String was equal to System.Boolean.TrueString.");
        }
        else {            
            System.Console.WriteLine(
                "String was equal to System.Boolean.FalseString.");
        }
    }
    catch (System.FormatException exp) {        
        System.Console.WriteLine(
            ("The string must equal System.Boolean.TrueString "  
            + "or System.Boolean.FalseString."));
    }

    // A conversion from bool to string will always succeed.
    stringVal = System.Convert.ToString(boolVal);
    System.Console.WriteLine("{0} as a string is {1}", 
        System.Convert.ToString(boolVal), stringVal);
} //ConvertStringBoolean

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft