Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there another "is" operator in C#? [duplicate]

I was teaching my students how to write a function. I used a simple algorithm to determine if a char value is an actual letter (and not a digit or something else).

So I actually typed what my student said (playing dumb on purpose): "if (letter is 'A') {...}" To my surprise this didn't cause a compiler error. I added the same check for 'B' and 'C' and my program can now determine that A, B and C are indeed letters.

Why does that work? And WHAT exactly am I comparing here? I'm not actively using type comparisons, which is what the internet keeps turning up.

I did an additional experiment with other values:

 char l = 'A';
 if (l is 'A')
 {
    Console.WriteLine("l 'A'...");
 }
 if (l is "A")
 {
    // Doesn't compile.
 }

 int x = 15;
 if (x is 15)
 {
    Console.WriteLine("X is 15.");
 }
 if (x is 5.6)
 {
    // Also doesn't compile.
 }

As far as I can tell "is" functions as an extended version of the equality (==) operator that also enforces the same type. But I can't find any documentation on it.

like image 466
Frederik Bonte Avatar asked Sep 16 '20 15:09

Frederik Bonte


Video Answer


1 Answers

is might have two meanings, depending on which version of C# you have.

In older C# versions, is was short for "is assignable to" or "is assignable from", depending on how you read the code in your head. It wouldn't work for the code in your class because it expects a type on the right-hand side, but I include it here for completeness. It's also useful as an efficient and portable null check, ie variable is object is a better way to write variable != null1.

In newer C# versions, is can also be used for pattern matching. This was introduced in C# 72 and extended in C# 8, with more coming in 9. Specifically, the code in the question creates a Constant Pattern expression.

Here's another fun way to see this work. Coming in C# 9, instead of writing a check like this:

if (!string.IsNullOrEmpty(mystring))

You could instead write3

if (mystring is {Length:>0})

Which is nice because it's shorter and you could make an argument removing the negation makes it easier to understand.4


  1. At least, according to one of the developers on the C# team at Microsoft. But what would he know? He only built the thing.
  2. Really, C# 6 if you count exception filters.
  3. Jared Parsons again.
  4. I'd reject that argument on the grounds any gains in removing the negation are less than the subtlety introduced in how we validate for null. But you could try the argument ;) And before anyone asks, I have no idea at this time how the two options perform.
like image 83
Joel Coehoorn Avatar answered Oct 31 '22 15:10

Joel Coehoorn