Home > Mobile >  Why casting to IEnumerable<T> when passing list to another list as constructor?
Why casting to IEnumerable<T> when passing list to another list as constructor?

Time:07-30

I saw the following code:

this.list = new List<GameObject>((IEnumerable<GameObject>) this.someVar.otherList);

where otherList is declared as follows:

public List<GameObject> otherList = new List<GameObject>();

Why do we need to cast the list passed to the constructor to (IEnumerable<GameObject>), what exactly is happening here?

CodePudding user response:

You don't have to do that, ever. The constructor takes IEnumerable<T>, and that's what it gets - regardless of whether you do the cast explicitly (new List<GameObject>((IEnumerable<GameObject>)otherList) or implicitly (new List<GameObject>(otherList)).

The only reason where you'd want to be explicit is if there were multiple overloads, e.g. if there was an overload that took List<GameObject> and you specifically wanted to use th IEnumerable<GameObject> overload for some reason.

If the code was generated, it would be understandable to have the explicit cast. If it was handwritten, someone needs to review their knowledge of C# :)

CodePudding user response:

This was not necessary. I don't know why it was done, but the List constructor takes IEnumerable objects. A list is already an IEnumerable object, so the cast was redundant.

  • Related