tags:

views:

366

answers:

11

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.

+8  A: 
bool b = true;
Console.WriteLine(b.ToString());
Sergey Teplyakov
I think something's missing ;) This is the code that works for me: `Console.WriteLine((false == !(b == true)).ToString());`
Ben Voigt
@Ben Voight: and you can read that can you?
annakata
It only makes sense inside the magic delimiters: ;) and );
Ben Voigt
+2  A: 

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

MikeP
+2  A: 

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

bool myBool = false;
string myString = myBool.ToString();
abelenky
+1  A: 

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.

lincolnk
I don't think "find it on this page" really counts as an answer. Comments are more appropriate for tips (and for cynical jabs).
jball
@jball it's tagged as "homework" and I am under the impression that standard procedure here is not to do all the work for the OP. is that wrong?
lincolnk
The OP references using an `if ... else ...` structure which implies that they can solve the homework on their own, but just want to know if there is a better/easier way. There is debate about the correct way to help with homework, but generally I think this question is so far away from the "How do I solve a complex problem for my homework" that the answer can just be given.
jball
I think your answer would have made a fine comment.
jball
+13  A: 

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);
Mark Byers
c# doesn't do implicit conversion, so `string + bool` won't work.
lincolnk
Yes C# doesn't do implicit conversion, it calls ToString method instead.
Sergey Teplyakov
@lincolnk: String.Concat (which is what is used in the first case) has overloads taking `object` parameters, so the presented code does work very well. (documentation: http://msdn.microsoft.com/en-us/library/kbseaaft.aspx)
Fredrik Mörk
has that always been the case? how did I not know that?
lincolnk
@lincolnk: You can't do a direct implicit conversion (`string s = true;` will not work). However, `String.Concat` will (I presume) invoke `ToString` to obtain string representations, so `string s = true + "";` will work (string concatenation with `+` will make the compiler emit `String.Concat` calls). It's not an implicit conversion.
Fredrik Mörk
Although the code works, I personally find it preferable to actually spell out .ToString(). Easier on my eyes.
Chris Lively
@Chris Lively - Also, calling the `string` rather than `object` overload on `String.Concat` is a micro-optimization that avoids boxing the bool (in this case). That makes me feel better about the code for some reason.
Jeffrey L Whitledge
A: 
  bool myBool = true;  
  MessageBox.show(myBool.toString());
Thomas Langston
A: 

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

Ryan Ternier
Really? a -1? Oh well :\
Ryan Ternier
you forgot to reference http://dotnetperls.com/convert-bool-int
dbones
+5  A: 

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" 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.

Jon Hanna
bump - generated javascript is one of the common cases for stringifying bools. On the latter point, this would just be a matter of passing `(val ? "yes" : "no")` as an argument to a format string.
annakata
@annakata, on the latter point no, there are languages that don't even have words that translate to yes and no in them (Irish, Scots Gaelic; while "ta" and "nil" are offered in Irish referenda, they wouldn't be a good translation in a wider sentence) and many where the rest of the sentence might have to be modified in some way. As a rule you need to have the complete sentences in your resource.
Jon Hanna
Having done some work in Irish in the past, I'm now a little worried about the state of UAT at the time... :P
annakata
@annakata, will depend on the context. If there was a field that in the English had just said "yes" or "no", then likely translating that as "ta" or "nil" will have done fine. In wider clauses it doesn't work so well (why those of us who don't even speak Irish are more likely to say "I am" than "yes" compared to English speakers elsewhere, it's a trace from our fluent-Irish ancestors).
Jon Hanna
A: 

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.

Murven
A: 
var booleanVal = true;

if (booleanVal == True) 
{
    stringVal = "True";
} 
else if (booleanVal == False)
{
    stringVal = "False";
}
else
{
    throw new System.ArgumentException("Boolean is neither true or false!");
}
Rogue
Fine, but you forgot to handle the FileNotFound case.
Johann Blais
+1  A: 

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

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