views:

285

answers:

3

I posted an answer to this question, including a very short rant at the end about how String.Split() should accept IEnumerable<string> rather than string[].

That got me thinking. What if the base Object class from which everything else inherits provided a default implementation for IEnumerable such that everything now returns an Enumerator over exactly one item (itself) -- unless it's overridden to do something else like with collections classes.

The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array.

I'm sure there are all kinds of reasons not to do this, not the least of which is that if everything implemented IEnumerable, then the few classes where the implementation strays from the default could behave differently than you'd expect in certain scenarios. But I still thought it would be a fun exercise: what other consequences would there be?

A: 

the index operator ([]) isn't part of the contract of IEnumerable<T> After looking at the code in reflector, the code uses the index operator heavily, which is always part of Array.

Well, simply put, Array will always have an enumerator.

The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array.

That isn't true, string inherits IEnumerable<char> And you don't have generic variance, so you can't cast IEnumerable<char> to IEnumerable<string>. You would be getting the IEnumerable<char> version(s) of split, rather then the required string.

MagicKat
However, I'd prefer it if string.Join accepted IEnumerable rather than string[] as it stands now.
Jeff Yates
It is an implementation detail. If IEnumerable support the index operator (which it doesn't) I am sure that it would be used.
MagicKat
A: 

Have you thought about using a helper object and implementing a Split for the IEnumerable class?

I did once make a GetDescription for the Enum class so to get the DescriptionAttribute easily. It works amazingly well.

Leahn Novash
+2  A: 
public static IEnumerable<object> ToEnumerable(this object someObject)
{
    return System.Linq.Enumerable.Repeat(someObject, 1);
}
David B