1

I need to understand the meaning of !is in c#. I understand the is keyword. I expected that a !is b would be the same as !(a is b). However, after testing, I found out that this is not the case. I just need to know what it means and when it may be useful.

I have checked the documentation for is.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is

From the navigation, it appears the only type testing keyword is is. There's no obvious reference to !is. I can find none in the same page as is, yet the compiler doesn't fail when I use !is. (Is this a bug?).

previousStageResult.Data is defined as object.

// this
var previousResultIsInvalid = previousStageResult.Data !is Dictionary<string, int>;

// returns the same thing as
var previousResultIsInvalid = previousStageResult.Data is Dictionary<string, int>;
// What I expect:
var previousResultIsInvalid = previousStageResult.Data !is Dictionary<string, int>;

// should be the same as
var previousResultIsInvalid = !(previousStageResult.Data is Dictionary<string, int>);

// if it is even valid at all

Thank you.

staa99
  • 191
  • 1
  • 2
  • 13
  • 4
    `!is` doesn't mean anything. It's not a keyword. – canton7 Oct 21 '19 at 15:57
  • 3
    Postfix-! on a non-nullable reference in c#8 and later is the [null-forgiving operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving). It's a postfix operator on the reference to the left of the `is`; it isn't a boolean negation of the `is` – 15ee8f99-57ff-4f92-890c-b56153 Oct 21 '19 at 15:59
  • 2
    yeah, this is "test whether blah.Data, which I definitely think isn't null, is a dictionary" - in terms of parens, it is `(previousStageResult.Data!) is Dictionary`; which is pointless, because `is` doesn't care whether values are `null` or not :) – Marc Gravell Oct 21 '19 at 16:01
  • 3
    this is a fun question, but sadly it is based on a false premise... – Marc Gravell Oct 21 '19 at 16:04
  • 3
    @MarcGravell Even more sadly, it's already a duplicate. – 15ee8f99-57ff-4f92-890c-b56153 Oct 21 '19 at 16:05
  • Thank you everyone. I had thought the `!` was an operator on the is. Now I understand better. Just to clarify I tested `a!is b` and I find it valid, although it's unreadable. – staa99 Oct 21 '19 at 20:19

0 Answers0