C# `is` operator issue

I am seeing a difference between Elements C# and Microsoft’s C# around the is operator.

This program:

namespace Test
{
    class Person
    {
        
    }
    
    static class Program
    {
        public static Int32 Main(string[] args)
        {
            var p = new Person();
            
            if (p is null)
            {
                Console.WriteLine("Oh dear");
            }
        }
    }
}

Compiles on Visual Studio 2019 on the Mac but fails to compile in Fire (macOS Island console app). The error I get in Fire is:

If I change p is null to p == null then Fire compiles but why the difference between the two implementations?

What is that supposed to do? is is a type check, not equality. null is not a type.

The example I provided is contrived. Where I’ve used it before is to check that an object passed as a constructor argument isn’t null. I don’t mind using ==null instead of is null but the VC# compiler accepts both. I think the edge case that the is operator avoids issues if you’ve also overridden the == method for a class.

Hm,. that makes no logical sense though. is does not check for equality.

…later…

ahh, kill me now (emphasis mine):

The is operator checks if the result of an expression is compatible with a given type, or (starting with C# 7.0) tests an expression against a pattern.
The `is` operator - Match an expression against a type or constant pattern - C# | Microsoft Learn

what the actual frack!?

Thanks, logged as bugs://84587

That said:

I think if you have a buggy == overload, then you’ll have bigger problems that that :wink:

1 Like

It is an odd use of is and my C# experience is young and being shaped by crappy StackOverflow answers :slight_smile:

1 Like

apparently “if (x is 3)” works too, but bypasses the equality operator. insanity.

It seems it’s from C# 7.0: https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching

Yep. stupidest thing i’ve ever seen (ok, thats a lie. there’s always Swift ;). but still…)

1 Like

It has some initially odd-seeming side-effects, but far from crazy imho. And ironically this seems to fit with C# increasingly embracing English-like syntax, more commonly associated with … Pascal (see also: not, and + or in C# 9).

I guess they’ve finally run out of hieroglyphs to construct out of the standard symbols on a Roman character-set keyboard. :slight_smile:

I’m keen to hear why you’re not a fan of Swift. You clearly know languages so it’d be interesting.

:exploding_head:

bugs://84587 got closed with status fixed.