- I have a generic class A<T>, that implements IEnumerable<T[]>.
I want to have a convenience wrapper B that inherits from A<char> and implements IEnumerable<string>.
public class A<T> : IEnumerable<T[]> { public IEnumerator<T[]> GetEnumerator() { return Enumerate().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } protected IEnumerable<T[]> Enumerate() { throw new System.NotImplementedException(); } } public class B : A<char>, IEnumerable<string> { public IEnumerator<string> GetEnumerator() { return Enumerate().Select(s => new string(s)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Now, this works perfectly fine, foreach variable type is inferred to be string:
B b = new B();
foreach (var s in b)
{
string[] split = s.Split(' ');
}
But this won't compile, saying "The type arguments cannot be inferred from usage, try specifying the type arguments explicitly":
string[] strings = b.ToArray();
However, this works:
string[] strings = b.ToArray<string>();
Can anyone explain this compiler behavior?
Obviously, B implements both IEnumerable<char[]> and IEnumerable<string> and probably it can't figure out which of them I want to call, but why it works fine in "foreach" sample?
Please, don't suggest me to solve my problem by composition - this is the last resort for me.