Skip to content

Latest commit

 

History

History
59 lines (43 loc) · 2.15 KB

File metadata and controls

59 lines (43 loc) · 2.15 KB

PH2116: Avoid ArrayList

Property Value
Package Philips.CodeAnalysis.MaintainabilityAnalyzers
Diagnostic ID PH2116
Category Maintainability
Analyzer AvoidArrayListAnalyzer
CodeFix Available
Severity Error
Enabled By Default Yes

Introduction

The ArrayList should be avoided. It doesn't use generics and therefore suffers from performance issues when used with structs. Structs need to be boxed into a class on every call to ArrayList, which impacts the performance negatively.

Microsoft discourages the use of ArrayList for this reason, as can be read on MS Learn.

How to solve

Microsoft provides an alternative in the List<> class, which is supporting generics and doesn't suffer from the boxing issue. Otherwise List<> is equivalent in usage to ArrayList. In this sense, it can be regarded as a plug-in replacement.

The CodeFixer does the replacement of ArrayList with List<> for you. The generic type cannot be deduced however so the CodeFixer triggers a rename dialog for the user to specify this generic type.

Example

Code that triggers a diagnostic:

using System.Collections;
class BadExample 
{
    private ArrayList _list = new ArrayList();

    public void Add(int item) 
    {
        _list.Add(item);
    }
}

And the replacement code:

using System.Collections.Generic;
class GoodExample 
{
    private List<int> _list = new List<int>();

    public void Add(int item) 
    {
        _list.Add(item);
    }
}

Configuration

This analyzer does not offer any special configuration. The general ways of suppressing diagnostics apply.