I'm a newbie to programming and .net, and I am having a hard time understanding why using the List<T>(IEnumerable<T>)
constructor accepts an array created using []
, but does not accept an array created using Array.CreateInstance(Type, Int32)
.
Here is what works:
DirectoryInfo[] dirsArray = foo.GetDirectories();
List<DirectoryInfo> dirsList = new List<DirectoryInfo>(dirsArray);
Here is what doesn't:
Array dirsArray = Array.CreateInstance(typeof(DirectoryInfo), 10); //assume we know 10 is the required length
List<DirectoryInfo> dirsList = new List<DirectoryInfo>(dirsArray);
The above gives the following compiler errors:
Error 1 The best overloaded method match for 'System.Collections.Generic.List<System.IO.DirectoryInfo>.List(System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo>)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'System.Array' to 'System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo>'
But I know that List<T>(IEnumerable<T>)
can accept any IEnumerable
as an argument. And I know that System.Array
is IEnumerable
. Not only because that is in the reference, but because the first example using the []
constructor syntax works fine.
So then what is the problem here? Does Array.CreateInstance
somehow manages to create an array that is not IEnumerable
?