Parses a string intended to represent a boolean value. - CSharp System

CSharp examples for System:String Parse

Description

Parses a string intended to represent a boolean value.

Demo Code

//  Copyright ? 2011, Grid Protection Alliance.  All Rights Reserved.
using System.Text.RegularExpressions;
using System.Text;
using System.IO;//from   w  w  w. ja  va  2s . com
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Parses a string intended to represent a boolean value.
        /// </summary>
        /// <param name="value">String representing a boolean value.</param>
        /// <returns>Parsed boolean value.</returns>
        /// <remarks>
        /// This function, unlike Boolean.Parse, correctly parses a boolean value, even if the string value
        /// specified is a number (e.g., 0 or -1). Boolean.Parse expects a string to be represented as
        /// "True" or "False" (i.e., Boolean.TrueString or Boolean.FalseString respectively).
        /// </remarks>
        public static bool ParseBoolean(this string value)
        {
            if (string.IsNullOrEmpty(value))
                return false;

            value = value.Trim();

            if (value.Length > 0)
            {
                // Try to parse string a number
                int iresult;

                if (int.TryParse(value, out iresult))
                {
                    return (iresult != 0);
                }
                else
                {
                    // Try to parse string as a boolean
                    bool bresult;

                    if (bool.TryParse(value, out bresult))
                    {
                        return bresult;
                    }
                    else
                    {
                        char test = value.ToUpper()[0];
                        return (test == 'T' || test == 'Y' ? true : false);
                    }
                }
            }

            return false;
        }
}

Related Tutorials