Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

in-keyword #316

Closed
IAmTheCShark opened this issue Mar 22, 2017 · 3 comments
Closed

in-keyword #316

IAmTheCShark opened this issue Mar 22, 2017 · 3 comments

Comments

@IAmTheCShark
Copy link

C# really could use an in or alternatively is in keyword like other languages (e.g. TSQL) offer.

It allways feels wrong writing code like

if (new[] {1,2,3,4}.Contains(id)) {

}

if (id == 1 || id == 2 || id == 3 || id == 4) {

}

switch(id)
{
   case 1: case 2: case 3: case 4: {  ...  } break;
}


public static bool IsIn<T>(this T value, params T[] values) => values.Contains(value);

if(id.IsIn(1,2,3,4)) {

}

when this would feel / look so much better

if (id in { 1,2,3,4 }) {

}

The compiler should be able to generate something like the switch statement out of this so that there is no arraycreation involved like the extensionmethod does.

Making it work for Enumerables is a bonus

if (id in listOfIds) {
}

where the compiler should just translate it into Enumerable.Contains

I think this is connected to Discussion: Range operator #198

@DavidArno
Copy link

Active patterns (coupled with Permit IEnumerable as the type of a params parameter) would completely cover this use case (and many, many more);

public bool InPattern<T>(this IEnumerable<T> collection, T matchValue) =>
    collection.Contains(matchValue);

...
if (id is In(1,2,3,4)) 
{
}

switch(id)
{
   case In(1,2,3,4) : ...
}

@alrz
Copy link
Member

alrz commented Mar 23, 2017

Active patterns are not extremely useful here a regular extension method works just fine,

static bool In<T>(this T value, params T[] values) { .. }

if (value.In(1, 2, 3)) 

unless you want to use it in a switch statement.

OR patterns (#118) can also be helpful.

@IAmTheCShark
Copy link
Author

IAmTheCShark commented Mar 24, 2017

@alrz I know it is nitpicking but the extensionmethod comes with a few "drawbacks"
Most important to mention is the array creation, while my idea of that keyword was to avoids this.

Apart from that you might need a reference to the assembly where that extensionmethod is located plus a using statement to make it avaible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants