1. The use of C# 7.0 and previous is
is
The operator checks if the result of the expression is compatible with the given type, or (starting from C# 7.0) tests the expression based on the pattern. About type testsis
For operator information, see TypeTest and type conversion operatorsArticleis operatorpart.
1.is pattern matching
Starting with C# 7.0,is
andswitch
Statements support pattern matching. Shouldis
Keywords support the following modes:
Type mode: It tests whether an expression can be converted to a specified type, and if so, cast it to a variable of that type.
(Constant) Constant Mode: Used to test whether the expression is evaluated to the specified constant value.
var mode: The match is successful and the value of the expression is bound to the match of the new local variable.
Starting with C# 7.1,expr
Possibly have compile-time types defined by common type parameters and their constraints.
ifexpr
yestrue
andis
andif
Use statements together,varname
Allocated only within the if statement.varname
The scope is fromis
Expression to includeif
The end of the block of the statement. Use in any other locationvarname
This results in a compile-time error when using variables that have not been allocated.
1) Type mode
When performing pattern matching using type mode,is
Tests whether an expression can be converted to a specified type, and if so, cast it to a variable of that type. This is rightis
Direct extension of statements allows concise type evaluation and conversion. The general form of is type pattern is:
expr is type varname
The following example uses the is type pattern to provide type(Object)Implementation of the method.
using System; public class Employee : IComparable { public String Name { get; set; } public int Id { get; set; } public int CompareTo(Object o) { if (o is Employee e) { return (); } throw new ArgumentException("o is not an Employee object."); } }
2) (Constant) Constant mode
When performing pattern matching with constant patterns, is tests whether the expression is equal to the specified constant. In C# 6 and earlier,switchStatements support constant mode. Starting with C# 7.0, this is statement also supports it. The syntax is:
expr is constant
The following example combines the type and constant patterns to test whether the object is a Dice instance, and if so, determines whether the value of the dice roll is 6.
using System; public class Dice { Random rnd = new Random(); public Dice() { } public int Roll() { return (1, 7); } } class Program { static void Main(string[] args) { var d1 = new Dice(); ShowValue(d1); } private static void ShowValue(object o) { const int HIGH_ROLL = 6; if (o is Dice d && () is HIGH_ROLL) ($"The value is {HIGH_ROLL}!"); else ($"The dice roll is not a {HIGH_ROLL}!"); } } // The example displays output like the following: // The value is 6!
null
You can use the (Constant) constant to check. This statementnull
Support keywordsis
. The syntax is:
expr is null
Sample code:
using System; class Program { static void Main(string[] args) { object o = null; if (o is null) { ("o does not have a value"); } else { ($"o is {o}"); } int? x = 10; if (x is null) { ("x does not have a value"); } else { ($"x is {}"); } // 'null' check comparison ($"'is' constant pattern 'null' check result : { o is null }"); ($" 'null' check result : { (o, null) }"); ($"Equality operator (==) 'null' check result : { o == null }"); } // The example displays the following output: // o does not have a value // x is 10 // 'is' constant pattern 'null' check result : True // 'null' check result : True // Equality operator (==) 'null' check result : True }
3) var mode
Patterns matching var pattern are always successful. Its syntax is:
expr is var varname
expr
The value ofvarname
local variables.varname
Yes withexpr
variable of the same type as compile time.
ifexpr
The calculation result isnull
,butis
Expression generationtrue
Andnull
Assign tovarname
. var mode isis
One of the few null values generatedtrue
One of the usages.
You can use the var pattern to create a temporary variable in a boolean expression, as shown in the following example:
using System; using ; using ; class Program { static void Main() { int[] testSet = { 100271, 234335, 342439, 999683 }; var primes = (n => Factor(n).ToList() is var factors && == 2 && (1) && (n)); foreach (int prime in primes) { ($"Found prime: {prime}"); } } static IEnumerable<int> Factor(int number) { int max = (int)(number); for (int i = 1; i <= max; i++) { if (number % i == 0) { yield return i; if (i != number / i) { yield return number / i; } } } } } // The example displays the following output: // Found prime: 100271 // Found prime: 999683
2. The new syntax of is in C# 8.0
Attribute mode
Match any non"null"
The object with the property set to Length is 2, the sample code is as follows:
if (value is { Length: 2 }) { }
Examples of implementing verification:
public async Task<IActionResult> Update(string id, ...) { if (ValidateId(id) is { } invalid) return invalid; ... }
In the example above,ValidateId()
Can returnnull
orBadObjectRequestResult
An example of . If the former is returned, the verification is successful and transferred to the rest of the update body. If the latter is returned,is{}
True (that is, of courseBadObjectRequestResult
The instance of , is an object ), and the verification failed.
If you use the general writing method to make a judgment, more code may be needed, as follows:
public async Task<IActionResult> Update(string id, ...) { var invalid = ValidateId(id); if (invalid != null) return invalid; ... }
Related Documents:The `is` operator - Match an expression against a type or constant pattern - C# | Microsoft Learn
This is the article about the introduction and use summary of the new syntax "is {}" in C#8.0. For more related content in C#8.0, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!