CodeQL documentation

Cast from abstract to concrete collection

ID: cs/cast-from-abstract-to-concrete-collection
Kind: problem
Severity: warning
Precision: medium
   - 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.


Consider using the abstract collection’s methods and remove the cast.


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;

    static IEnumerable<string> GetNames()
        var ret = new List<string>()
        return ret;