Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Why can a string[] be passed as IEnumerable<string> parameter?

This is valid code:

void func(IEnumerable<string> strings){
    foreach(string s in strings){
        Console.WriteLine(s);
    }
}

string[] ss = new string[]{"asdf", "fdsa"};
func(ss);

What I want to know is, how does the implicit conversion string[] -> IEnumerable<string> work?

like image 452
Cristian Diaconescu Avatar asked Nov 30 '22 07:11

Cristian Diaconescu


1 Answers

from: msdn Array Class

In the .NET Framework version 2.0, the Array class implements the

  • IList<T>,
  • ICollection<T>, and
  • IEnumerable<T>

generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

like image 156
Daren Thomas Avatar answered Dec 11 '22 00:12

Daren Thomas