0

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?

Community
  • 1
  • 1
Todd Li
  • 3,209
  • 21
  • 19

1 Answers1

3

X509Certificate2Collection.getEnumerator() returns an X509Certificate2Enumerator, which has a Current property of type X509Certificate2.

In other words, c# is not relying solely on IEnumerable or IEnumerable<T>. It's looking at that Current property directly.

http://msdn.microsoft.com/en-us/library/aa288257%28v=vs.71%29.aspx

j__m
  • 9,392
  • 1
  • 32
  • 56