2

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?

iabbott
  • 873
  • 1
  • 8
  • 23
srm
  • 3,062
  • 16
  • 30
  • 1
    base class will already store `models`. Why do you need `_models.AddRange(models);` ? – I4V Sep 01 '13 at 19:36
  • a) I need/want to store locally because although parent class does store, it stores as base class and I want to avoid downcasting when I use it locally. b) It is not a duplicate of that question. – srm Sep 03 '13 at 03:25

1 Answers1

6

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?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Simple and great answer – Amiram Korach Oct 03 '13 at 11:14
  • 1
    Actually, this answer has turned out to be a problem. It is creating an extra copy of the enumeration. When the list got very large, that extra list is a bit of an issue. Having two copies (one in parent and one in child), fine, but three copies -- that temporary created just to call the base class -- that's a problem. I'm not sure how we're going to refactor to handle it, but I wanted to record here that although this is a good solution for the general problem, it does have a downside. – srm Aug 26 '14 at 18:34