0

I have a method similar to this:

void Log(object value)
{
    if (value is IEnumerable && !(value is IList))
    {
        // Need to convert value to a list here
    }

    // ... Rest of code here
}

As the comment says, I need to check if the value passed in is actually an IEnumerable and convert it to a List if it is.

The problem is that the IEnumerable's generic type could be anything. Application classes, .Net Library classes, even anonymous projections via a linq select statement.

How can I convert an IEnumerable (without knowing its generic type) to a List?

IMPORTANT: This is using the full .Net Framework 4.x. NOT .Net Core.

FYI: This is in legacy code. The reason that I need to do this is because the library we use to serialize our logs (YAX) has a memory leak with IEnumerables. But we have found that if we convert to a List then the memory leak does not happen.

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 4
    Does this answer your question? [Converting from IEnumerable to List](https://stackoverflow.com/a/7617784/902497) – Raymond Chen Nov 19 '20 at 19:17
  • @RaymondChen I'm pretty sure it want as OP does not seem to know the type - their most likely need code method that let's them call `ToList` without knowing type first... (unless `List` is enough) – Alexei Levenkov Nov 19 '20 at 19:19
  • Closed as duplicate for now - Vaccano - please clarify if `List` is enough (as covered in the duplicate). [edit] the question if you need something else. – Alexei Levenkov Nov 19 '20 at 19:22
  • 1
    @AlexeiLevenkov - a `List` is enough. Thanks for the help. – Vaccano Nov 19 '20 at 19:26

0 Answers0