Skip to content

Commit b029251

Browse files
committed
Add documentation for the GCI95 rule
This is for green-code-initiative/creedengo-csharp#92
1 parent 458ab17 commit b029251

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/main/rules/GCI95/GCI95.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
----

0 commit comments

Comments
 (0)