Skip to content

Commit d60b7c7

Browse files
committed
C#: Improve empty collection check to not report on collections with property writes
1 parent 399da68 commit d60b7c7

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

csharp/ql/src/semmle/code/csharp/commons/Collections.qll

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,8 @@ private predicate readonlyAccess(Access a) {
143143
// A read-only method call
144144
exists(MethodCall mc | mc.getQualifier() = a | mc.getTarget().hasName(readonlyMethodName()))
145145
or
146-
// Any property access
147-
a = any(PropertyAccess pa).getQualifier()
146+
// Any property read
147+
a = any(PropertyRead pr).getQualifier()
148148
or
149149
// An element read
150150
a = any(ElementRead er).getQualifier()

csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,21 @@ void f8(object arguments)
152152
break;
153153
}
154154
}
155+
156+
void f9()
157+
{
158+
var l1 = new MyList(); // BAD
159+
var x1 = l1[0];
160+
161+
var l2 = new MyList(); // GOOD
162+
var x2 = l2[0];
163+
l2.Prop = 42;
164+
}
165+
166+
class MyList : List<int>
167+
{
168+
public int Prop { get { return 0; } set { Add(value); } }
169+
}
155170
}
156171

157172
// semmle-extractor-options: /r:System.Collections.dll

csharp/ql/test/query-tests/ReadOnlyContainer/ReadOnlyContainer.expected

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@
88
| ReadOnlyContainer.cs:91:13:91:14 | v8 | The contents of this container are never initialized. |
99
| ReadOnlyContainer.cs:96:13:96:14 | v9 | The contents of this container are never initialized. |
1010
| ReadOnlyContainer.cs:99:13:99:15 | v10 | The contents of this container are never initialized. |
11-
| ReadOnlyContainer.cs:121:13:121:15 | v11 | The contents of this container are never initialized. |
11+
| ReadOnlyContainer.cs:121:13:121:15 | v11 | The contents of this container are never initialized. |
12+
| ReadOnlyContainer.cs:158:13:158:14 | l1 | The contents of this container are never initialized. |

0 commit comments

Comments
 (0)