Skip to content

Commit f0d70f3

Browse files
committed
C#: Add null conditional tests.
1 parent 503a1b5 commit f0d70f3

File tree

6 files changed

+59
-0
lines changed

6 files changed

+59
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System;
2+
3+
public class C
4+
{
5+
public int Field;
6+
7+
public string Property { get; set; } = "";
8+
9+
public void M(C c, int[] numbers, bool b)
10+
{
11+
// Get values.
12+
var fieldValue = c?.Field;
13+
var propertyValue = c?.Property;
14+
var n = numbers?[0];
15+
16+
// Set values
17+
c?.Field = 42;
18+
c?.Property = "Hello";
19+
numbers?[0] = 7;
20+
21+
// Set values using operators
22+
c?.Field -= 1;
23+
c?.Property += " World";
24+
25+
// Using the return of an assignment
26+
var x = c?.Field = 10;
27+
28+
// Using in a conditional expression
29+
int? maybenull = 0;
30+
maybenull = (b ? c : null)?.Field;
31+
}
32+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
| NullConditional.cs:30:22:30:33 | ... ? ... : ... |
2+
| NullConditional.cs:30:30:30:33 | null |
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import csharp
2+
import semmle.code.csharp.dataflow.Nullness
3+
4+
from MaybeNullExpr mne
5+
where mne.getFile().getBaseName() = "NullConditional.cs"
6+
select mne
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
| NullConditional.cs:12:26:12:33 | access to field Field |
2+
| NullConditional.cs:13:29:13:39 | access to property Property |
3+
| NullConditional.cs:14:17:14:27 | access to array element |
4+
| NullConditional.cs:17:9:17:16 | access to field Field |
5+
| NullConditional.cs:18:9:18:19 | access to property Property |
6+
| NullConditional.cs:19:9:19:19 | access to array element |
7+
| NullConditional.cs:22:9:22:16 | access to field Field |
8+
| NullConditional.cs:22:9:22:16 | access to field Field |
9+
| NullConditional.cs:23:9:23:19 | access to property Property |
10+
| NullConditional.cs:23:9:23:19 | access to property Property |
11+
| NullConditional.cs:26:17:26:24 | access to field Field |
12+
| NullConditional.cs:30:21:30:41 | access to field Field |
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import csharp
2+
3+
from QualifiableExpr e
4+
where e.isConditional()
5+
select e
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
semmle-extractor-options: /nostdlib /noconfig
2+
semmle-extractor-options: --load-sources-from-project:${testdir}/../../resources/stubs/_frameworks/Microsoft.NETCore.App/Microsoft.NETCore.App.csproj

0 commit comments

Comments
 (0)