What is the access modifier of an explicit implementation?

Asked

Viewed 64 times

3

I created an iterator class that implements the interface IEnumerable<T>, implementing the interface IEnumerable. To make the implementation correctly, it is necessary to explicitly implement the method IEnumerable.GetEnumerator, as in the code below:

public class MyClasst<T> : IEnumerable<T> {
    private int[] list = {1, 2, 3, 4, 5};

    IEnumerator IEnumerable.GetEnumerator() {
        return this.GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator() {
        for (int i = 0; i < Count; i++) {
            yield return this.list[i];
        }
    }

Note that in the implementation of the non-generic interface method, no access modifier is declared. Whenever I put any access modifier - public, internal, protected or private - the compiler generates an error, stating that it is not allowed.

That said, my question is:

  • What access modifier is defined by the compiler for this type of implementation?
  • Is it possible to access this method specifically, whether inside or outside the class? If so, how should the method be invoked?

1 answer

5


Explicit interface implementation is always public (see language specification). There is no reason not to be, and decided that since it is the only way, it would not allow to say in the code that it is, because in a way it is as if it were private to the interface. It’s confusing, and I talk about it in link down below.

It is not possible to access the specific implementation by the class directly, only through the interface, but using it can access without problems anywhere.

using static System.Console;
using System.Collections;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var x = new MyClasst<int>();
        WriteLine(((IEnumerable)x).GetEnumerator());
        WriteLine(x.GetEnumerator());
    }
}

public class MyClasst<T> : IEnumerable<T> {
    private T[] list;
    
    public IEnumerable Teste() => (IEnumerable)GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() {
        WriteLine("Explícita");
        return this.GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator() {
        yield return this.list[0];
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Note that calling directly does not call the explicit implementation.

The code was written only to demonstrate the mechanism, it has no practical functionality and should not be used like this. This yield does not seem to be correct (even if it works), but I will not say without seeing the whole.

More on the subject: What is the purpose of an explicit C interface implementation#?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.