Cast from abstract to concrete collection¶
ID: cs/cast-from-abstract-to-concrete-collection
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- reliability
- maintainability
- modularity
- external/cwe/cwe-485
Query suites:
- csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Casting from an abstract collection to a concrete implementation is bad practice. It makes your code fragile because it becomes more difficult to change which implementation you are using at a later date.
Recommendation¶
Consider using the abstract collection’s methods and remove the cast.
Example¶
The example shows casting from an IEnumerable<string>
to a List<string>
. This should be avoided where possible.
using System.Collections.Generic;
class Bad
{
public static void Main(string[] args)
{
var names = GetNames();
var list = (List<string>) names;
list.Add("Eve");
}
static IEnumerable<string> GetNames()
{
var ret = new List<string>()
{
"Alice",
"Bob"
};
return ret;
}
}
References¶
C# Corner, C# Interface Based Development.
Common Weakness Enumeration: CWE-485.