views:

39

answers:

2

Is there some way of detecting whether an enumerable built using LINQ (to Objects in this case) have been materialized or not? Other than trying to inspect the type of the underlying collection?

Specifically, since enumerable.ToArray() will build a new array even if the underlying collection already is an array I'm looking for a way of avoiding ToArray() being called twice on the same collection.

A: 

Checking "is IEnumerable" can do this, there isn't another way. You could, however, not use the "var" declaration for the return type - because it is "hiding" from you the type. If you declare an explicit IEnumerable, then the compiler will let you know if that is what is being returned.

Brent Arias
Var doesn't hide anything from you, it's just a shorthand so you don't have to type out the type yourself. When the code is compiled, the type will be the exact type would've declared yourself.
Femaref
I put "hiding" in quotes for a reason. If you declare the exact type you want, the compiler can provide an error if you did not achieve the type that you intended. That is all I meant by "hiding."
Brent Arias
Checking for `IEnumerable` doesn't help since that is what I already have. Perhaps my question wasn't clear enough, but I want to take an `IEnumerable` and check whether it have been materialized (converted to a list or array) or not.
Peter Lillevold
+1  A: 

The enumerable won't have an "underlying collection", it will be a collection. Try casting it to one and use the resulting reference:

var coll = enumerable as ICollection<T>;
if (coll != null) {
    // We have a collection!
}
Marcelo Cantos
Yes, of course, this solution does not tie me to specific implementations of IEnumerable. Thanks!
Peter Lillevold