0

Can someone explain how an intereface can be forced to be implemented as private or public. Usually when I define an interface, every method/property are public. In the example, using "IEnumerable" produce a public method "GetEnumerator()" but using the interface "IEnumerable" the method "IEnumerable.GetEnumerator()" is private by default.

public class customEnumerable<T> : IEnumerable<T>, IEnumerable
{

    public IEnumerator<T> GetEnumerator()
    {
        throw new NotImplementedException();
    }

    IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

Thanks!

Nacho
  • 65
  • 8
  • All methods defined in an interface are public, because an interface defines a public contract. Private methods are an implementation detail, so they have no place in an interface. – Dennis_E Jul 30 '14 at 09:53
  • `IEnumerable.GetEnumerator()` is not at all private, it can be accessed only via interface instance, that is the difference – Sriram Sakthivel Jul 30 '14 at 09:53
  • the public method way of implementing the interface is called Implicit implementaion and `IEnumerable.GetEnumerator()` way of implementing is called Explicit implementation. Refer the link mentioned by Iridium for more clarity – Ramesh Jul 30 '14 at 09:56
  • Visual Studio create the above code using the "implement interface" option. I can see in the related question that using the "explicit" option it won´t populate the methods as public – Nacho Jul 30 '14 at 10:05

1 Answers1

4

A private member makes no sense as part of an interface as all methods defined in an interface are public. An interface is there to define a set of methods, a role, an object must always implement.

Private methods are just the implementation details and they are not intended for public consumption.

As per MSDN

The CLR also allows an interface to contain static methods, static fields, constants, and static constructors. However, a CLS-compliant interface must not have any of these static members because some programming languages aren’t able to define or access them. In fact, C# prevents an interface from defining any static members. In addition, the CLR doesn’t allow an interface to contain any instance fields or instance constructors.

For more details you may refer this:- C# Interfaces. Implicit implementation versus Explicit implementation

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331