DEV Community

Miro 💻
Miro 💻

Posted on

The myth of C#'s *is* operator (== null or is null)

Alt Text

This relates to the current roslyn compiler at 30.11.2020

After two years as C# Developer I almost never see C#'s is operator in code reviews or tutorials.

Most developer sticks to the always known comparison operators (==, !=).

But there definitely also myths like the is operator does not act like a good old == or is less efficient.

That's why i tested it with a decompiler and here are my results!

Compile == and is

var a = "test string";

if (a == null) throw new InvalidOperationException();

if (a is null) throw new InvalidOperationException();
Enter fullscreen mode Exit fullscreen mode

Results in:

string text = "test string";
if (text == null)
{
    throw new InvalidOperationException();
}
if (text == null)
{
    throw new InvalidOperationException();
}
Enter fullscreen mode Exit fullscreen mode

both is compiled to the same result with the current version of the Roslyn Compiler.

Compile != and C#'s 9 is not

var a = "test string";

if (a != null) throw new InvalidOperationException();

if (a is not null) throw new InvalidOperationException();
Enter fullscreen mode Exit fullscreen mode

Results in:

string text = "test string";
if (text != null)
{
    throw new InvalidOperationException();
}
if (text != null)
{
    throw new InvalidOperationException();
}
Enter fullscreen mode Exit fullscreen mode

both is compiled to the same result with the current version of the Roslyn Compiler.

Compile != and !(a is null) (< C#9)

var a = "test string";

if (a != null) throw new InvalidOperationException();

if (!(a is null)) throw new InvalidOperationException();
Enter fullscreen mode Exit fullscreen mode

Results in:

string text = "test string";
if (text != null)
{
    throw new InvalidOperationException();
}
if (text != null)
{
    throw new InvalidOperationException();
}
Enter fullscreen mode Exit fullscreen mode

both is compiled to the same result with the current version of the Roslyn Compiler.

Result:

Both results in the same when your code compiles so its up to you with operator you prefer.

Question:

What is the way you prefer?

for more C# or dev related Posts follow me on Twitter :)

Top comments (0)