Search code examples
c#casting

Convert Char To Boolean


In C++ is assumed to be false while all other values are true. I was under the impression that in C# this concept was the same.

I'm trying to convert a char to a bool.

char c = (char)0;
Convert.ToBoolean(c).Dump();

It seems like no matter what char I try to convert I always get an error

Invalid cast from 'Char' to 'Boolean

I understand what I can to to fix this if I write my own custom function, but what I am trying to understand is.

What is the purpose of this method, What Char value converts to Bool?


Solution

  • You stated:

    I was under the impression that in C# this concept was the same.

    You were mistaken. It isn't. The two languages behave differently in that way, and you simply cannot convert a Char to a Boolean.

    The documentation makes it clear that the method always fails:

    Calling this method always throws InvalidCastException.

    and...

    Return Value

    Type: System.Boolean

    This conversion is not supported. No value is returned.

    As evidenced by the source for Char.ToBoolean():

    [__DynamicallyInvokable]
    bool IConvertible.ToBoolean(IFormatProvider provider)
    {
        object[] values = new object[] { "Char", "Boolean" };
        throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", values));
    }
    

    As the Char class inherits from IConvertible, it is required to provide the overload. But since this conversion is not possible, an exception is always returned.