Convert string "1" or "0" to bool true or false

Viewed 13623

Convert.ChangeType("1", typeof(bool)) return a runtime-error

is there any way to override this behavior?

I would like Convert.ChangeType("1", typeof(bool)) returntrue Convert.ChangeType("0", typeof(bool)) return false

UPDATE
reading comments and answers maybe I have not been clear enough

Suppose to have a dictionary of <object,Type> where type is the target type

foreach (var element in dictionary)
{
   object convVal = Convert.ChangeType(element.Key, element.Value);
}

when element.Key is "1" and elemen.Value is bool I would like to get true

Anyone can give me any suggestions to implement a similar behavior

At least something better that this:

 public static class Convert
    {
        public static object ChangeType(object val, Type type)
        {
            if (val is string && type == typeof(bool))
            {

                switch (((string)val).Trim().ToUpper())
                {
                    case "TRUE":
                    case "YES":
                    case "1":
                    case "-1":
                        return true;

                    default:
                        return false;
                }
            }
            return System.Convert.ChangeType(val, type);
        }
    }

Can TypeConverter be the right way?

Please think before to post comments or answers or mark question as duplicated

5 Answers
Convert.ToBoolean(Convert.ChangeType("1", typeof(uint)));
Related