Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does is operator behave like == operator?

Tags:

c#

Assume we have statement like this:

enum EngineType
{
   Gasoline,
   Diesel,
   Electric
}

var engine = EngineType.Electric;

if (engine is EngineType.Electric)
{
    // do something
}

Why does if statement is true. From microsoft documentation: The is operator checks if the result of an expression is compatible with a given type.

Isn't the left value type of EngineType (enum) and right value type of integer? Am I missing something?

like image 707
fnsky Avatar asked Sep 20 '25 07:09

fnsky


2 Answers

Because when you use the is keyword this way, you are actually doing Pattern Matching (starting with C# 7.0) :

Constant pattern, which tests whether an expression evaluates to a specified constant value.

like image 73
Martin Verjans Avatar answered Sep 22 '25 20:09

Martin Verjans


Because is in C# 7.0 supports pattern matching. In particular, it allows matching against a "constant pattern". To quote from the documentation (emphasis mine):

When performing pattern matching with the constant pattern, is tests whether an expression equals a specified constant. In C# 6 and earlier versions, the constant pattern is supported by the switch statement. Starting with C# 7.0, it's supported by the is statement as well. Its syntax is:

expr is constant

where expr is the expression to evaluate, and constant is the value to test for. constant can be any of the following constant expressions:

  • A literal value.

  • The name of a declared const variable.

  • An enumeration constant.

like image 24
Heinzi Avatar answered Sep 22 '25 19:09

Heinzi