Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Char To Boolean

Tags:

c#

casting

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?

like image 476
johnny 5 Avatar asked May 22 '26 05:05

johnny 5


2 Answers

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.

like image 132
DonBoitnott Avatar answered May 23 '26 20:05

DonBoitnott


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);
}
like image 32
Eser Avatar answered May 23 '26 20:05

Eser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!