Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in operator in C#

Tags:

syntax

c#

enums

I think there was an in operator in Commodore 128 Basic.
Is there an in operator in c# too?

I mean is there an operator of kind

if(aString in ["a", "b", "c"])  
  Console.Out.WriteLine("aString is 'a', 'b' or 'c'");

Edit1: Currently I need it to decide if an enum value is in a range of some enum values.

Edit2: Thank you all for the Contains() solutions. I will use it in the future. But currently I have a need for enum values. Can I replace the following statement with Contains() or other methods?

public enum MyEnum { A, B, C }

class MyEnumHelper
{
  void IsSpecialSet(MyEnum e)
  {
    return e in [MyEnum.A, MyEnum.C]
  }
}

Edit3: Sorry it was not Basic. I just googled a while and found Turbo Pascal as a candidate where I could saw it. See http://en.wikipedia.org/wiki/Pascal_%28programming_language%29#Set_types

Edit4: Best answers up to now (end of 15 Feb 2012):

  • For lists and arrays: accepted answer and all other answers with Contains() solutions
  • For Enums: TheKaneda's answer with good list of pros/cons for different extension methods
like image 965
brgerner Avatar asked Feb 15 '12 19:02

brgerner


People also ask

What is an operator in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What is the in operator used for?

The SQL IN condition (sometimes called the IN operator) allows you to easily test if an expression matches any value in a list of values. It is used to help reduce the need for multiple OR conditions in a SELECT, INSERT, UPDATE, or DELETE statement.

What is << in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .


1 Answers

Try this:

if(new [] {"a", "b", "c"}.Contains(aString))  
    Console.Out.WriteLine("aString is 'a', 'b' or 'c'");

This uses the Contains method to search the array for aString.

like image 109
Andrew Hare Avatar answered Oct 19 '22 20:10

Andrew Hare