- Home /
Convert bool to char in C#
Hi I want to convert a bool to a char. The standard method in C# seems [1] to be
bool vIn = true;
char vOut = Convert.ToChar(vIn);
But for me Unity3D produces the following error:
System.Convert.ToChar (Boolean value)
InvalidCastException: This conversion is not supported.
I am using the System namespace of course. Thanks for any help. I am a C#/Unity3D rookie.
[1] http://www.convertdatatypes.com/Convert-bool-to-char-in-CSharp.html
@FrojoS, it says that the conversion is not supported because there's no natural conversion from a boolean to an unicode character. What do you think the result should be ? Convert true to '1' and false to '0' ? Convert true to 't' and false to 'f' ? Both don't really make sense. The real question here is, what do you want to do with the resulting char?
Answer by Rnd-- · Sep 27, 2012 at 10:09 AM
try this
char vOut = (vIn == true ? '1' : '0');
I'm almost sure that's the most efficient way ;) Oh, btw: You don't have to compare a bool to true. It is already a boolean expression itself ;)
char vOut = (vIn ? '1' : '0');
Answer by DocteurCox · Sep 27, 2012 at 09:15 AM
Did not know that bool.toString() didn't exist but whatever. I guess you could just create a simple static method to parse boolean to string :
static string BoolToString(bool b)
{
return b ? "true":"false";
}
Just put it in an Util class and you would just have to do Util.BoolToString(b)
Hope it helped ;)
Hi, he want convert to char, no to string.
@FrojoS: I you want to convert to string use vIn.ToString(). This function exist and you become "true" or "false" as result.
oops, didn't read properly :x Well he can just use my method with a char return type and the values he wants.
@DocteurCox: Do you have a Java background? ;) because Java uses lower camel case while in C# you usually use upper camel case. In Java there's the function toString in C# / .NET it's ToString
Ohh, of course Java is not UnityScript (Unity's Javascript)
Answer by sebstar · Sep 27, 2012 at 09:36 AM
Hi,
try this:
bool vIn = false; char vOut = (char)Convert.ToByte(vIn);
this runs for me.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Convert a char to int / float 2 Answers
I can't figure out why this if statement isn't responding 1 Answer
Enemy spawn, round based 1 Answer