简体   繁体   中英

What's the easiest way to convert from a bool to string in C#?

I am tempted to use an if ... else ... but I am wondering if there's an easier way? I need to display the true or false result in a message box.

The bool.ToString method already does what you want.

This method returns the constants "True" or "False".

However in practice it is not that often that you need to explicitly call ToString directly from your code. If you are already writing a string then the easiest way is to use concatenation:

string message = "The result is " + b;

This compiles to a call to string.Concat and this calls the ToString method for you.

In some situations it can be useful to use String.Format , and again the ToString method is called for you:

string message = string.Format("The result is {0}. Try again?", b);
bool b = true;
Console.WriteLine(b.ToString());

I'm just going to throw:

val ? "true" : "false"

into the mix, as having a lowercase result is often necessary (a lot of machine-readable formats, such as a lot of XML formats, use lower case "true" and "false" for boolean values) and the above is faster and also IMO cleaner than val.ToString().ToLowerInvariant() .

Of course, extension to val ? "yes" : "no" val ? "yes" : "no" and so on is trivial. To be localisable is another matter, and not always trivial (quite a few cases would have quite different sentences if translated well, so the logic of messageStart + (val ? "yes" : "no") + messageEnd doesn't always work well.

bool v = true;  
string s = v.ToString();

What is wrong with .ToString() , which is available on every object?

bool myBool = false;
string myString = myBool.ToString();

This is a one-liner. All c# types derive from Object and so inherit the methods of that class.

I'll point you here: http://msdn.microsoft.com/en-us/library/system.object.aspx and let you find it.

  bool myBool = true;  
  MessageBox.show(myBool.toString());

It is always recommended to use static functions under Convert class. In your case

bool boolValue = true; System.Convert.ToString(boolValue);

If you want to make it fully localizable, you can add a resource file called UiStrings to the project and add an entry for each of the boolean values. Visual Studio will generate a wrapper (using either PublicResXFileCodeGenerator or ResXFileCodeGenerator) for the resource manager, which you can then access using static properties.

Then, you can use it like this:

var booleanValue = true;  
var booleanText = booleanValue ? UiStrings.TrueValueText : UiStrings.FalseValueText;  
var messageText = UiString.ResultMessageText;  
var messageString = String.Format("{0}:{1}", messageText, booleanText);

The verbose code is intentional so that you can identify the different parts.

I know you didn't ask this, but for the heck of adding my own narcissistic voice to the mix, this is how to you get an int from a bool (0, 1)

using System;

class Program
{
    static void Main()
    {
        // Example bool is true
        bool t = true;

        // A
        // Convert bool to int
        int i = t ? 1 : 0;
        Console.WriteLine(i); // 1

        // Example bool is false
        bool f = false;

        // B
        // Convert bool to int
        int y = Convert.ToInt32(f);
        Console.WriteLine(y); // 0
    }
}

Output:

1

0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM