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?
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.BooleanThis 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.
Just to show how it can be done with unsafe keyword (similar to c++). Don't use this..
char c = (char)0;
unsafe{
bool b = *((bool *)&c);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With