Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast T to bool and vice versa

I have the following extensionmethods for strings to be able to do this ("true").As<bool>(false) Especially for booleans it will use AsBool() to do some custom conversion. Somehow I can not cast from T to Bool and vice versa. I got it working using the following code however it does seem a bit of overkill.

It's about this line:
(T)Convert.ChangeType(AsBool(value, Convert.ToBoolean(fallbackValue)), typeof(T))
I would rather use the following, but it will not compile:
(T)AsBool(value, (bool)fallbackValue), typeof(T))

Am I missing something or is this the shortest way to go?

    public static T As<T>(this string value)
    {
        return As<T>(value, default(T));
    }
    public static T As<T>(this string value, T fallbackValue)
    {
        if (typeof(T) == typeof(bool))
        {
            return (T)Convert.ChangeType(AsBool(value,
                                                Convert.ToBoolean(fallbackValue)),
                                                typeof(T));
        }
        T result = default(T);
        if (String.IsNullOrEmpty(value))
            return fallbackValue;
        try
        {
            var underlyingType = Nullable.GetUnderlyingType(typeof(T));
            if (underlyingType == null)
                result = (T)Convert.ChangeType(value, typeof(T));
            else if (underlyingType == typeof(bool))
                result = (T)Convert.ChangeType(AsBool(value,
                                                Convert.ToBoolean(fallbackValue)),
                                                typeof(T));
            else
                result = (T)Convert.ChangeType(value, underlyingType);
        }
        finally { }
        return result;
    }
    public static bool AsBool(this string value)
    {
        return AsBool(value, false);
    }
    public static bool AsBool(this string value, bool fallbackValue)
    {
        if (String.IsNullOrEmpty(value))
            return fallbackValue;
        switch (value.ToLower())
        {
            case "1":
            case "t":
            case "true":
                return true;
            case "0":
            case "f":
            case "false":
                return false;
            default:
                return fallbackValue;
        }
    }
like image 689
Silvermind Avatar asked Aug 24 '12 13:08

Silvermind


People also ask

What is convert ToBoolean?

ToBoolean(Object) Converts the value of a specified object to an equivalent Boolean value. ToBoolean(Decimal) Converts the value of the specified decimal number to an equivalent Boolean value.


1 Answers

You can cast it to object and then to T:

if (typeof(T) == typeof(bool))
{
  return (T)(object)AsBool(value, Convert.ToBoolean(fallbackValue));
}
like image 77
Stefan Avatar answered Nov 06 '22 23:11

Stefan