File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ {
2+ "title" : " Use 'is' operator instead of 'as' operator and null check" ,
3+ "type" : " CODE_SMELL" ,
4+ "status" : " ready" ,
5+ "remediation" : {
6+ "func" : " Constant/Issue" ,
7+ "constantCost" : " 1min"
8+ },
9+ "tags" : [
10+ " roslynator" ,
11+ " readability" ,
12+ " simplification" ,
13+ " performance"
14+ ],
15+ "defaultSeverity" : " Minor"
16+ }
Original file line number Diff line number Diff line change 1+ Using the `as` operator followed by a null check is more verbose and can be simplified using the `is` operator with pattern matching.
2+
3+ When using the `is` pattern, the type check and cast happen in one concise statement, improving readability and reducing boilerplate.
4+
5+ Therefore, using `is` with pattern matching will simplify code and improve maintainability.
6+
7+ == Non compliant Code Example
8+
9+ [source,csharp]
10+ ----
11+ var myObj = obj as MyType;
12+ if (myObj != null)
13+ {
14+ myObj.DoSomething();
15+ }
16+ ----
17+
18+ == Compliant Code Example
19+
20+ [source,csharp]
21+ ----
22+ if (obj is MyType myObj)
23+ {
24+ myObj.DoSomething();
25+ }
26+ ----
27+
28+ [source,csharp]
29+ ----
30+ var anotherObj = maybeObj as AnotherType;
31+ if (anotherObj != null)
32+ {
33+ Console.WriteLine(anotherObj.Value);
34+ }
35+ ----
36+
37+ == Compliant Code Example
38+
39+ [source,csharp]
40+ ----
41+ if (maybeObj is AnotherType anotherObj)
42+ {
43+ Console.WriteLine(anotherObj.Value);
44+ }
45+ ----
You can’t perform that action at this time.
0 commit comments