String was not recognized as a valid Boolean

String was not recognized as a valid Boolean


String was not recognized as a valid Boolean


 The string representation of boolean values ("true" , "False" ) can be parsed to compare with actual boolean values (true , false).
If the input string contains invalid format of boolean values ("1", "0" or Null ), you get an unhandled exception as "String was not recognized as a valid Boolean"

  protected void Button1_Click(object sender, EventArgs e)
    {

        string strCheck = "True";

        if (bool.Parse(strCheck))
        {
            Response.Write("Working on");
        }     

    }
    
Output: Working on

  In above example I have used string "xyz" and when application starts to analyse the string content
it throws an exception.

Code:

  protected void Button1_Click(object sender, EventArgs e)
    {
        string strCheck = "xyz";
        
        bool result;

        if (bool.TryParse(strCheck,out  result ))
        {
            Response.Write("Working on");
        }

        Response.Write(result.ToString());
    }      
  
Output: False

Description:
TryParse method accepts two parameters first one is actual string and second is parsed results.
If the string is in ininvalid format or Null, result comes False.

It also handles exception of type
Null reference exception was unhandled

 

 

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5