How do I make a string such as "You did it!" appear from a boolean pass/fail instead of just "True" or "False"? I'm only ever able to find the ToString method, but all that does is change "True" to "true". I want to know how to make the string output whatever I want.
We can convert boolean to String in java using String. valueOf(boolean) method. Alternatively, we can use Boolean. toString(boolean) method which also converts boolean into String.
The Boolean. ToString() method in C# converts the value of this instance to its equivalent string representation (either "True" or "False").
A string is a type of variable that represents a series of characters (i.e. text.) A boolean is a type of variable that represents one of two possible values, either true of false.
The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true');
A bool
is a type, the same way a string
is a type. You'll never be able to get a bool type to show "You did it!", because its a bool - it can only be true or false.
What you want is to create a string based on the result of boolean. Sounds like you want an if
statement:
string myString;
if(myBool) // if true
{
myString = "You did it!";
}
else
{
myString = "You didn't do it";
}
like @juharr showed, there are ways to do this in less lines of code, but this is the logic that needs to happen.
As a side note, you see the ToString
method on bool
because every type inheriting from System.Object
inherits the ToString
method, providing you with a string representation of that object. It's not applicable for what you're wanting to accomplish here.
If you are using C# 3.0 or higher, you can also put this in an extension method for bool like this:
public static string ToDidItOrNotString(this bool b)
{
return b ? "You did it!" : "You did not do it.";
}
Then you can just call it like this:
string s = boolVal.ToDidItOrNotString();
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