Reputation: 199
I'm trying to change the "Keyword" of a boolean (true/false), I mean when I write at console.
For example:
What I want:
What I have:
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);
}
Upvotes: 0
Views: 6597
Reputation: 21
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")
Upvotes: 2
Reputation: 66439
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);
Upvotes: 1
Reputation: 649
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.
Upvotes: 0
Reputation: 218818
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);
Upvotes: 1