Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So I have quite a newbie question:
What if I want to say like:

if (dog != "cat" or "cow")
{
   Console.WriteLine("A dog is not equal to a cow nor a cat!");
}

And 'II' cannot be used since I am using strings.

What I have tried:

I tried the II but since I have a string it wouldn't work
Posted
Updated 17-Jan-17 7:29am
Comments
[no name] 17-Jan-17 12:30pm    
if (dog != "cat" && dog != "cow")

You would have to say:
C#
if (dog != "cat" && dog != "cow")
Or
C#
if (!(dog == "cat" || dog == "cow"))
 
Share this answer
 
If you're going to need to do this frequently, especially if there are more than just a couple of items then you should make a function that does this:
C#
public static bool IsOneOf(string s, params string[] many)
{
  if (many == null)
    throw new ArgumentNullException("many");
  return ((IList<string>)many).Contains(s);
}
You would use it like:
C#
if (!IsOneOf(dog, "cat", "cow"))
{
   Console.WriteLine("A dog is not equal to a cow nor a cat!");
}
This is pretty basic.
A more advanced solution would be to make a generic extension method:
C#
public static class MyExtensionMethods
{
  public static bool IsOneOf<T>(this T s, params T[] many)
  {
    if (many == null)
      throw new ArgumentNullException("many");
    return ((IList<T>)many).Contains(s);
  }
}
You would use it like:
C#
if (!dog.IsOneOf("cat", "cow"))
{
   Console.WriteLine("A dog is not equal to a cow nor a cat!");
}
There are other ways to do this, some optimized for certain cases.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900