convert string to a bool value if possible, if failed, return false as default value. only true, yes or 1 will be treated to true value - CSharp System

CSharp examples for System:String Convert

Description

convert string to a bool value if possible, if failed, return false as default value. only true, yes or 1 will be treated to true value

Demo Code


using System.Xml;
using System.Web;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;// w  w  w  .jav a 2  s .  c o  m

public class Main{
        #endregion

        #region Convert
        /// <summary>
        /// convert string to a bool value if possible, if failed, return false as default value.
        /// <para>only true, yes or 1 will be treated to true value</para>
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <returns>a bool value</returns>
        public static bool ToBoolean(this string theSource)
        {
            return theSource.EqualsAny(StringComparison.OrdinalIgnoreCase, "true", "yes", "1");
        }
        /// <summary>
        /// check if the string is equals with any of the compare string.
        /// </summary>
        /// <param name="theSource">the source string</param>
        /// <param name="comparison">comparison type</param>
        /// <param name="compares">caompare strings</param>
        /// <returns>true or false</returns>
        public static bool EqualsAny(this string theSource, StringComparison comparison, params string[] compares)
        {
            return compares.Any(s => string.Equals(theSource, s, comparison));
        }
        /// <summary>
        /// check if the string is equals with any of the compare string.
        /// </summary>
        /// <param name="theSource">the source string</param>
        /// <param name="compares">caompare strings</param>
        /// <returns>true or false</returns>
        public static bool EqualsAny(this string theSource, params string[] compares)
        {
            return compares.Any(s => string.Equals(theSource, s));
        }
}

Related Tutorials