Skip to content

Commit b0e8a3f

Browse files
Repro for S2583 FP: Custom indexer and removal method (#9592)
1 parent e3a118b commit b0e8a3f

File tree

1 file changed

+58
-1
lines changed

1 file changed

+58
-1
lines changed

analyzers/tests/SonarAnalyzer.Test/TestCases/SymbolicExecution/Roslyn/ConditionEvaluatesToConstant.cs

+58-1
Original file line numberDiff line numberDiff line change
@@ -4321,10 +4321,67 @@ public void IndexerReturnsNullInsteadOfThrowingException(NameValueCollection col
43214321
if (element != null)
43224322
{
43234323
Console.WriteLine(element.ToString());
4324+
if (collection.Count == 0) // Noncompliant - the indexer returned a non-null result, so the collection is not empty
4325+
{
4326+
Console.WriteLine("Empty!"); // Secondary
4327+
}
43244328
}
4325-
if (collection.Count == 0) // Noncompliant - FP: the indexer with string argument returns null if the key is not found rather than throwing an exception,
4329+
if (collection.Count == 0) // Noncompliant - FP: the indexer returns null if the key is not found rather than throwing an exception,
43264330
{ // so at this point we can't know for sure that the collection is not empty.
43274331
Console.WriteLine("Empty!"); // Secondary - FP
43284332
}
43294333
}
4334+
4335+
public void IndexerReturnsNullInsteadOfThrowingException(PersonCollection collection)
4336+
{
4337+
var person = collection[42];
4338+
if (person != null)
4339+
{
4340+
person.RemoveFromGroup();
4341+
collection.Refresh();
4342+
4343+
if (collection.Count == 0) // Noncompliant - FP: the collection has custom removal logic that doesn't adhere to the ICollection<T> or other standard interfaces,
4344+
{ // so at this point it might have removed the only item from the collection, therefore it might be empty.
4345+
Console.WriteLine("Empty!"); // Secondary - FP
4346+
}
4347+
}
4348+
}
4349+
4350+
public class PersonCollection
4351+
{
4352+
internal readonly List<Person> persons;
4353+
4354+
public PersonCollection(List<Person> persons)
4355+
{
4356+
this.persons = persons;
4357+
}
4358+
4359+
public Person this[int index] => persons[index];
4360+
4361+
public int Count => persons.Count;
4362+
4363+
public void Add(Person person)
4364+
{
4365+
person.IsPartOfGroup = true;
4366+
persons.Add(person);
4367+
}
4368+
4369+
public void Refresh()
4370+
{
4371+
persons.RemoveAll(p => !p.IsPartOfGroup);
4372+
}
4373+
}
4374+
4375+
public class Person
4376+
{
4377+
internal bool IsPartOfGroup;
4378+
4379+
public string Name { get; set; }
4380+
public int Age { get; set; }
4381+
4382+
public void RemoveFromGroup()
4383+
{
4384+
IsPartOfGroup = false;
4385+
}
4386+
}
43304387
}

0 commit comments

Comments
 (0)