Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do so many named collections in .NET not implement IEnumerable<T>?

Tags:

c#

ienumerable

Random example:

ConfigurationElementCollection

.Net has tons of these little WhateverCollection classes that don't implement IEnumerable<T>, which means I can't use Linq to objects with them out of the box. Even before Linq, you'd think they would have wanted to make use of generics (which were introduced all the way back in C# 2 I believe)

It seems I run across these annoying little collection types all the time. Is there some technical reason?

like image 956
Erix Avatar asked Jan 09 '13 15:01

Erix


2 Answers

The answer is in the question title: "named collections". Which is the way you had to make collections type-safe before generics became available. There are a lot of them in code that dates back to .NET 1.x, especially Winforms. There was no reasonable way to rewrite them using generics, that would have broken too much existing code.

So the named collection type is type safe but the rub is System.Collections.IEnumerator.Current, a property of type Object. You can Linqify these collections by using OfType() or Cast().

like image 125
Hans Passant Avatar answered Oct 19 '22 04:10

Hans Passant


As Adam Houldsworth said in a comment already, you simply need to use the Cast<> method.

Example:

var a = new DogCollection();
var allFidos = a.Cast<Dog>().Where(d => d.Name == "Fido"); 
like image 36
MgSam Avatar answered Oct 19 '22 04:10

MgSam