Container contents are never initialized¶
ID: cs/empty-collectionKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - correctness - external/cwe/cwe-561Query suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Code that queries the contents of a collection (such asContainsKey orCount) is invoked on an object that is known to be empty. Such queries do not return interesting results, and may indicate missing code or a logic error.
Recommendation¶
Either remove the collection if it is unnecessary, or ensure that it contains the correct data.
Example¶
The following example code is supposed to return the name of the day, but does not work because the collectiondaysOfWeek is never populated. When this code is run, anArgumentOutOfRangeException exception is thrown.
classCalendar{IList<string>daysOfWeek=newList<string>();publicstringdayName(intday){returndaysOfWeek[day-1];}}
This problem is fixed by populating the variabledaysOfWeek with the correct data.
classCalendarFix{IList<string>daysOfWeek=newList<string>{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};publicstringdayName(intday){returndaysOfWeek[day-1];}}