c# - How to convert a string to a bool

String to bool
.net Convert class ToBoolean() method convert the specified string representation of a logical value (true or false) to its boolean equivalent. Convert class allow us to convert a base data type to another base data type. Convert.ToBoolean() method exists in System namespace.

Convert.ToBoolean(String) method require to pass a parameter named 'value'. this 'value' parameter value type is System.String. this 'value' represent a string that contains the value of either Boolean.TrueString or Boolean.FalseString.

the ToBoolean() method return value type is System.Boolean. it return 'true' if the parameter 'value' equals to TrueString. method retruns 'false' if parameter 'value' equals to FalseString or null. this method throw an exception named FormatException if parameter 'value' is not equal to TrueString or FalseString. this ToBoolean method ignore case, leading and trailing white space.

the following .net c# example code demonstrate us how can we convert a string to a boolean value in an asp.net application.

<%@ Page Language="C#" AutoEventWireup="true"%>  
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create a string variable.  
        string stringOfBoolean = "true";  
        Label1.Text = "string of boolean value..................<br />";
        Label1.Text += stringOfBoolean;

        //this line convert/parse/transform string to boolean.
        bool b = Convert.ToBoolean(stringOfBoolean);
        Label1.Text += "<br /><br />converted boolean from string.........<br />";
        Label1.Text += b;

        Label1.Text += "<br /><br />type of the current instance (boolean).........<br />";
        Label1.Text += b.GetType();
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - string to bool</title>    
    <form id="form1" runat="server">    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - string to bool
        <hr width="550" align="left" color="Gainsboro" />    
        <br /><br />  
            Text="string to bool"    
More c# examples