interface - why does implementation have to be public?

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

Below I've created an interface ... why do all implementations of the
methods have to be public? What if I want them to be private or protected?

public interface IOisWebPageStandard
{
void SomeMethod1();
void SomeMethod2();
void SomeMethod3();
}

Thanks!
Mark
 
Below I've created an interface ... why do all implementations of the
methods have to be public? What if I want them to be private or protected?

public interface IOisWebPageStandard
{
void SomeMethod1();
void SomeMethod2();
void SomeMethod3();
}

What's the point in having an interface (a "contract" between two
parties) if you don't want the other party to be able to see the method?
The goal of an interface is to define how the object can be accessed by
the outside world.

Private/protected stuff is an internal implementation detail to the
class and has no bearing on those that use the class.
 
Mark,
Below I've created an interface ... why do all implementations of the
methods have to be public? What if I want them to be private or protected?

You can use explicit implementation to have private methods

void IOisWebPageStandard.SomeMethod1() { ... }



Mattias
 
A bit of clarification.

Explicit interface implementation is about visibility, not about
accessibility. If you implement something explicitly, it doesn't show up as
a method on the class, but you can still access it through the interface.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Eric Gunnerson said:
A bit of clarification.

Explicit interface implementation is about visibility, not about
accessibility. If you implement something explicitly, it doesn't show up as
a method on the class, but you can still access it through the interface.

While I don't agree with the OP's idea of interface methods being
private or protected, it *would* make sense to allow an internal
interface, allowing code such as:

using System;

internal interface Foo
{
int X();
}

public class Test : Foo
{
internal int X()
{
return 0;
}

static void Main()
{
}
}

Strangely enough, change X in Test to be public rather than internal
works - the interface itself can be internal, but it can't be
implemented internally.

What's the reason for this?
 
Back
Top