Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing multiple IEnumerables in C#

Tags:

c#

ienumerable

I have a generic class, Class<T>, that implements IEnumerable<T>. T is also constrained to implement IConvertable.

I also want this class to be able to pretend to be a string-like object, so I want to implement IEnumerable<char>. However, IEnumerable<T> and IEnumerable<char> collide -- what happens if T is char?

Does anyone have any suggestions on how to accomplish this?

EDIT: Here's some clarification -- I'd like to be able to do the following:

public IEnumerator<T> GetEnumerator()
{
    for (var i = _offset; i < _offset + _length; i++)
        yield return _array[i];
}

public IEnumerator<char> GetEnumerator()
{
    for (var i = _offset; i < _offset + _length; i++)
        yield return _array[i].ToChar(null);
}
like image 789
David Pfeffer Avatar asked May 23 '26 12:05

David Pfeffer


1 Answers

Does anyone have any suggestions on how to accomplish this?

Declaration of generic types such that the base types can unify under construction is sometimes illegal and almost always a bad idea. Avoid, avoid, avoid.

My advice: if you want an object that acts like a string then either override ToString(), or declare an explicit (or, I suppose, implicit) conversion to string. If the user wants a sequence of chars then they can obtain one from the string.

like image 166
Eric Lippert Avatar answered May 25 '26 02:05

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!