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?
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.
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 theis
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With