Search code examples
c#ienumerableradix

In C#, how do I solve multiple enumeration warning when one use is in base constructor call?


The following code gives me a warning about possible multiple enumeration of IEnumerable:

public ClassName(IEnumerable<OtherClassName> models) : base(models)
{
    _models.AddRange(models);
}

The normal solutions for removing this warning do not work because of the "base" call. I cannot convert to a list because there is no place to store that list.

Is my only option to make the constructor take a list as a parameter? Is that recommended practice in this case?


Solution

  • Create another private constructor which takes List<OtherClassName> and call it using this keyword:

    public ClassName(IEnumerable<OtherClassName> models)
        : this(models.ToList())
    {
    }
    
    private ClassName(List<OtherClassName> models)
        : base(models)
    {
        _models.AddRange(models);
    }
    

    And make sure you really need to store models within your class. Maybe it's already stored in base class and you can use it from there?