Im creating a program that will only greet the person if named carley and zack.
string name1 = "Carley";
string name2 = "Zack";
Console.Write("What's your name? : ");
string name = Console.ReadLine();
if (name == name1)
{
Console.WriteLine("Glad to meet you " + name + "!");
}
else if (name == name2)
{
Console.WriteLine("Glad to meet you " + name + "!");
}
else
{
Console.WriteLine("press any key to exit.");
}
Console.Read();
Here I am, hoping to simplify the code by trying to put the evaluation of the input in one statement for the "if":
if (name == name1 && name2)
{
Console.WriteLine("Glad to meet you " + name + "!");
}
else
{
Console.WriteLine("press any key to exit.");
}
Console.Read();
But it says the AND (&&) cant be applied for boolean and string. Can you please explain and help me out with this code, and also figuring out, it can accept input regardless if it has upper and lowercase etc.
You can't use &&
to compare one value against two other values. You need two comparisons:
if (name == name1 && name == name2)
Also, &&
doesn't match the logic in your original code. ||
would be the equivalent of your original code:
if (name == name1 || name == name2)
and also figuring out, it can accept input regardless if it has upper and lowercase etc.
You can use name.Equals(..., StringComparison.InvariantCultureIgnoreCase)
for a case insensitive comparison:
if (name.Equals(name1, StringComparison.InvariantCultureIgnoreCase) ||
name.Equals(name2, StringComparison.InvariantCultureIgnoreCase))
Since this is starting to get a bit verbose, you can put the acceptable names into an array and then use .Any()
. This approach will allow you to specify any number of valid names:
string[] validNames = new[] { "Carley", "Zack" };
if (validNames.Any(n =>
n.Equals(name, StringComparison.InvariantCultureIgnoreCase)))
{
// ...
}
But given that this approach is a bit advanced for your level, you may want to stick to the second-to-last snippet for now.