To Bool from String - CSharp System

CSharp examples for System:String Convert

Description

To Bool from String

Demo Code


using System;//from w  w  w. ja  v  a 2  s  . c  o  m

public class Main{
        public static bool ToBool(this string str)
        {
            // "true" | "false", "True" | "False" , 1 | 0, "tRue", "falSe"
            if (str.Length == 0)
                throw new InvalidOperationException();
            if (str.Length == 1)
            {
                int v;
                try
                {
                    v = int.Parse(str);
                }
                catch (Exception) { throw new InvalidOperationException(); }
                return v == 1;
            }
            str = str.ToLower();

            if (str == "true")
                return true;
            if (str == "false")
                return false;
            throw new InvalidOperationException();
        }
}

Related Tutorials