Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"is" operator compile-time warning

Tags:

c#

warnings

From the reference:

The is keyword causes a compile-time warning if the expression is known to always be true.

I tried to create an example:

class MyClass
{
    public void method(MyClass c)
    {
        if (c is MyClass)
        {
            //...
        }

        if (c is Object)
        {
            //...
        }
    }
}

But I don't get any warnings. Why?

Can someone show me an example where I get a warning (because the expression is always true)?

It works for false.

like image 732
otisonoza Avatar asked Mar 20 '23 04:03

otisonoza


1 Answers

The is operator will return false if the value is null, so if you call method(null) it would not enter either if-block.

However, if MyClass were actually a struct (i.e. not nullable), this would produce a warning.

like image 184
p.s.w.g Avatar answered Apr 01 '23 06:04

p.s.w.g