Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the "or" operator with strings in an "if" statement

Tags:

string

c#

is there anyway of fixing this statement

if (sAwnser == ("hello" || "Hello" || "hi" || "Hi" || "hey" || "Hey" || "Hay" || "hey"))
{

}

it comes up with the error

Operator '||' cannot be applied to operands of type 'string' and 'string'

if anyone can help it would be much appreciated

like image 966
user2947576 Avatar asked Nov 28 '22 04:11

user2947576


2 Answers

For avoiding so many comparisons you can do

var list = new string[] {"hello", "Hello", "hi", "Hi", "hey", "Hey", "Hay", "hey"};

if (list.Contains(answer))
{
}
like image 55
Esteban Elverdin Avatar answered Dec 15 '22 14:12

Esteban Elverdin


You have to explicitly reference the first variable every time.

sAwnser == "hello" returns a boolean. You cannot compare a boolean to a string.

What you could do is create a collection and add all your separate strings to that. Afterwards you can use .Contains() on it.

like image 37
Jeroen Vannevel Avatar answered Dec 15 '22 14:12

Jeroen Vannevel