Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String from Boolean

Tags:

c#

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.

like image 584
AdmiralCuddles Avatar asked Apr 01 '16 19:04

AdmiralCuddles


People also ask

Can you convert a boolean to string?

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.

Can we convert boolean to string in C#?

The Boolean. ToString() method in C# converts the value of this instance to its equivalent string representation (either "True" or "False").

Is boolean same as string?

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.

How do you change a string from boolean to true?

The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true');


2 Answers

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.

like image 166
Jonesopolis Avatar answered Oct 22 '22 03:10

Jonesopolis


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();
like image 44
Ionian316 Avatar answered Oct 22 '22 03:10

Ionian316