简体   繁体   中英

Change “Key word” (true/False) to “Yes/no” -Boolean C#

I'm trying to change the "Keyword" of a boolean (true/false), I mean when I write at console.

For example:

What I want:

  • Q: Was this song bought?
  • R: Yes

What I have:

  • Q: Was this song bought?
  • R: True

I don't want to write "true" I want to write "yes" and that C# can understand it.

Code:

public void questionBought(string miQuestion)
{
    Console.ForegroundColor = ConsoleColor.Green;
    string temporal;
    bool variableBool;
    Console.WriteLine(miQuestion);
    Console.ForegroundColor = ConsoleColor.Gray;
    temporal = Console.ReadLine();
    variableBool = Convert.ToBoolean(temporal);
    this.setBought(variableBool);
}

Your current code:

variableBool = Convert.ToBoolean(temporal);

Is equivalent to:

variableBool = (temporal == "true");

Similarly, you can test for equality against any string you choose:

variableBool = (temporal == "yes");

Better yet, ignore case (so user can type "yes", "YES", "Yes", etc) during comparison by using:

variableBool = temporal.Equals("yes", StringComparison.CurrentCultureIgnoreCase);

C# by itself doesn't "understand" the human-intended meanings of strings. Any string is just a string. You can, however, examine those strings for expected values. Something like this:

temporal = Console.ReadLine();
if (temporal.ToLower().Equals("yes"))
    variableBool = true;
else if (temporal.ToLower().Equals("no"))
    variableBool = false;
else
    Console.WriteLine("Unable to parse response.");
this.setBought(variableBool);

If you are doing it in a Razor View you can do the following:

@((item.variableBool) ? "Yes" : "No") 

And if it is a nullable bool and assuming it always has a value:

@(((bool)item.variableBool) ? "Yes" : "No")

There are a number of ways to accomplish this. You are reading into a string so just check what the string is equal to.

You can try something like this:

temporal = Console.ReadLine();
if (temporal.Equals("yes"))
{
   variableBool = true;
}
else
{
   variableBool = false;
}

Since String.Equals returns a bool value this can be shortened to:

temporal = Console.ReadLine();
variableBool = temporal.Equals("yes");

To further help this be more robust and accept any kind of casing, such as "Yes", "yes", "YeS" you can convert it to lowercase before checking equality:

temporal = Console.ReadLine();
variableBool = temporal.ToLower().Equals("yes");

There are many ways to solve this so try looking up some others.

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