0

I decompiled(go to the sources in vs using resharper) IEnumerable<T> and it contains the following code: (some not related code is omitted here)

public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

Actually I was researching about c# new modifier and I was surprised cause IEnumerable<T> doesn't contain it since IEnumerable<out T> inherits IEnumerable.

Than I decided to find a real(not decompiled) sources. I went here and found the following code:

public interface IEnumerable<out T> : IEnumerable
{
    new IEnumerator<T> GetEnumerator();
}

new modifier is here. But now I'm confused whether IEnumerable<T> contains new modifier or not and why there's the difference.

isxaker
  • 8,446
  • 12
  • 60
  • 87
  • 2
    The `new` is just there to suppress a compiler warning: Resharper's version will combine, but the compiler will give you a warning because the `IEnumerator GetEnumerator()` method shadows `IEnumerator GetEnumerator()` from `IEnumerable` – canton7 Jul 23 '20 at 15:44
  • But why do you think a `new` is needed here? – Tanveer Badar Jul 23 '20 at 15:44
  • 4
    @TanveerBadar Warning CS0108 hiding inherited member – isxaker Jul 23 '20 at 15:46
  • @canton7 so `new` here is just to prove our intention of hiding `GetEnumerator()` method from `IEnumerable` and nothing more - I mean practically there's no differences between `IEnumerable` with `new` and `IEnumerable` without `new`, right ? – isxaker Jul 23 '20 at 15:50
  • 1
    Correct. The warning is just the compiler saying "... are you sure?", and the `new` is a way for you to say "Yes, I'm sure". The compiled output will be the same in both cases. Resharper should really have realised that `new` is required in order to avoid that warning – canton7 Jul 23 '20 at 15:51
  • It's really a combination of two things: the need to ensure that the redeclared method is separate from the base interface method, and having done that, the need to make sure the compiler knows it was done on purpose (i.e. to prevent the warning). See separate duplicates for both the former and latter aspect. – Peter Duniho Jul 23 '20 at 16:36
  • You can also play around with [this SharpLab snippet](https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBLANgHwAEAmARgFgAoQgBgAJDSA6AYQl1xjA2wgDsAzgG4qtBqRQjKogMx1sfDDCgAzAIZgY4mQB4IAVwx0AKgD46IbVQDeVOvboBJAKJ99AW2VqM0HWboA4jAYrh5ePlAAFACUUgC+QA==) - having or removing the `new` modifier doesn't change the compiled IL code (shown on the right). – Joe Sewell Jul 23 '20 at 16:59
  • A method in a derived type cannot differ only by return type, if it does it will be considered the same method signature as an inherited method, and that's why the compiler will complain that you're shadowing the inherited method. – Lasse V. Karlsen Jul 23 '20 at 17:22

0 Answers0