Number Parity Expression Keyword #8526
-
Would adding language support for checking whether a number is odd or even have merit? So instead of using the modulo operator as we do now, we'd have a more expressive syntax. Moreover, in the lowered code, it would use the faster bitwise operation A rough draft of what it might look like is the following, although there are multiple other ways of doing if your concern is that expression keywords should be available to all types, not just numeric. if(myNumber is even)
{
// Handle even number
}
else if(myNumber is odd)
{
// Handle odd number
} OR something like this var num = 4;
if(num is { Even: true }) { ... } |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 12 replies
-
That is already legal type-test syntax. |
Beta Was this translation helpful? Give feedback.
-
public static class Int32Extensions
{
public static bool IsOdd(this int This) => This % 2 == 1;
public static bool IsEven(this int This) => This % 2 == 0;
}
int a = 123;
if(a.IsOdd())
{
} |
Beta Was this translation helpful? Give feedback.
-
@HaloFour Here is another question. Why does the design team disagree with having an operator for "is". Examples public struct Even
{
public static bool operator is(int number, Even e) => (number & 1) == 0;
}
public struct Odd
{
public static bool operator is(int number, Odd o) => (number & 1) == 1;
}
public struct Prime
{
public static bool operator is(int number, Prime p) => {...}
}
int num = 7;
var result = num switch
{
Even => $"{num} is even",
Odd => $"{num} is odd",
Prime => $"{num} is prime",
_ => $"{num} does not match any known condition"
};
Console.WriteLine(result); |
Beta Was this translation helpful? Give feedback.
Active patterns are something that the language team has expressed interest in.