Search code examples
c#.net.net-2.0

How to convert IList<string> to a string[] without using Linq


I'm not sure what is the best way to convert an IList<string> (IList does not implement the ToArray property) to an string[] array.

I cannot use Linq because I'm compiling with .NET 2.0. Any ideas will be wellcome.


Solution

  • Use ICollection<T>.CopyTo:

    string[] strings = new string[list.Count];
    list.CopyTo(strings, 0);
    

    I'm not quite sure if I understand the no-LINQ restriction though? It sounds like you would use ToArray if IList<T> had it. But it turns out it does because IEnumerable<T>.ToArray is an extension method defined on IEnumerable<T> of which IList<T> implements. So why don't you just use that?