There are many questions (1 2 3) about why var
picks up the object
type in a foreach
loop, but this time it's different. When I use this code snippet to loop through a X509Certificate2Collection
, it surprised me that var
actually picked up the X509Certificate2
type, instead of object
, although X509Certificate2Collection
only implements the non-generic IEnumerable
and not IEnumerable<T>
!
X509Certificate2Collection collection = new X509Certificate2Collection();
foreach (var cert in collection)
{
Console.WriteLine(cert.Subject);
}
You can see the inheritance hierarchy in the msdn article, but it doesn't seem to be implementing IEnumerable<X509Certificate2>
. If I use LINQ on the collection, I do not get the X509Certificate2
type:
collection.Select(cert => cert.Subject); // Won't compile
So how does the compiler know the actual type in the var
case?