53

In an interview a while ago for a .NET position the interviewer asked me "what would you use a private interface for?".

I asked him did he mean the difference between implicit vs explicit interface implementation to which he answered no.

So I'm wondering:

  1. What he meant?
  2. What you would use a private interface for?
guerda
  • 23,388
  • 27
  • 97
  • 146
RichardOD
  • 28,883
  • 9
  • 61
  • 81

5 Answers5

39

An interface could be private within another class

public class MyClass
{
    private interface IFoo
    {
        int MyProp { get; }
    }

    private class Foo : IFoo
    {
        public int MyProp { get; set; }
    }

    public static void Main(string[] args)
    {
        IFoo foo = new Foo();
        return foo.MyProp;
    }
}

in terms of utility it simply hides from other code, even within the same assembly, that said interface exists. The utility of this is not terribly high in my opinion.

Explicit interface implementation is a different matter, has some very useful cases (especially when working with generics and older non generic interfaces) but I would not term it 'private interfaces' and would not say that the term is commonly used in that manner.

Using the two techniques together you can do:

public class MyClass
{
    private interface IFoo
    {
        int MyProp { get; }
    }

    public class Foo : IFoo
    {
        int IFoo.MyProp { get; set; }
    }

    public static void Main(string[] args)
    {
        IFoo foo = new Foo();
        return foo.MyProp;
    }
}

public class HiddenFromMe
{
    public static void Main(string[] args)
    {
        MyClass.Foo foo = new MyClass.Foo();
        return foo.MyProp; // fails to compile
    }
}

This allows you to expose the nested classes in some fashion while allowing the parent class to invoke methods on them that the outside world cannot. This is a potentially useful case but is not something I would wish to use very often. Certainly it's use in an interview smacks of being a boundary case the interviewer is using because they've seen it and though it was 'interesting'

ShuggyCoUk
  • 36,004
  • 6
  • 77
  • 101
  • 7
    Though that is true, wouldn't that be one of the most useless usages of interfaces? I can't see why you would ever use such construction. – Razzie Apr 27 '09 at 10:13
  • struggling to think of much of a use case for that, or at least a use case which doesn't involve also creating a god class – annakata Apr 27 '09 at 10:15
  • That is what I interpreted the question as meaning, in which case it was just a silly question the interviewer asked! – RichardOD Apr 27 '09 at 10:15
  • 2
    I added a comment in the question about the utility (or lack thereof) I think the interviewer might have been using the wrong term for explicit interface implementation personally but that's a guess – ShuggyCoUk Apr 27 '09 at 10:19
  • Ah, just saw the comment from Graham on the other question, if it wasn't explicit implementation then I'm struggling to come up with a really good reason to use private interfaces... – ShuggyCoUk Apr 27 '09 at 10:20
  • 1
    Yeah I guess a good assumption is that he didn't know that explicit interface implementation == private interface. – RichardOD Apr 27 '09 at 10:22
  • 2
    @RichardOD: Not exactly ==. Explicit interface implementation doesn't necessarily mean that the methods implementing the interface are private. However, in private interface inheritance, they specifically are. Explicit implementation can be done with public methods of differing names (EG, "Close" being used to implement IDisposable.Dispose), with public members of the same name, or with private members. It is the latter case that truly creates the private interface inheritance -- you can't use the interface members WITHOUT casting to the interface. – John Rudy Apr 27 '09 at 11:12
  • 3
    Sorry John you're wrong about "Explicit interface implementation doesn't necessarily mean that the methods implementing the interface are private" read the linked doc in my answer specifically: "It is a compile-time error for an explicit interface member implementation to include access modifiers" and "Because explicit interface member implementations are never accessible through their fully qualified name in a method invocation or a property access, they are in a sense private. However, since they can be accessed through an interface instance, they are in a sense also public." – ShuggyCoUk Apr 27 '09 at 12:03
  • To be more specific if you have IFoo { void Do(); } and class Foo with two methods void Do(); and void IFoo.Do(); then the non explict Do method is *nothing* to do with the interface IFoo. You can invoke the method but only in the context where it is clear you have a Foo (or sub class thereof) the IFoo implementation is only called when the interface IFoo is the only way the compiler knows that Foo is a method on the object. This is one of why certain aspects of .Net use duck typing rather than force interface use... – ShuggyCoUk Apr 27 '09 at 12:09
  • ...(foreach doesn't use the IEnumerable.GetEnumerator() *method*, it uses duck typing to get to a specific GetEnumerator by various rules which allow it to pick a different GetEnumerator than the IEnumerable one) – ShuggyCoUk Apr 27 '09 at 12:10
  • I stand corrected. That's what I get for reading (and worse, posting) before caffeine! – John Rudy Apr 27 '09 at 19:23
  • @Shuggy- this to me is the best acceptable answer. I've finally got round to having my account merged so the answer can be accepted. In summary a really awful interview question that knocked my confidence for the rest of the interview! – RichardOD Aug 21 '09 at 09:48
10

From this link.

Private Interface Inheritance

Historically, languages have permitted private inheritance. In C++, you can inherit from a type without being polymorphically compatible with that type. It’s just a convenient way to reuse an implementation. In the CTS, you cannot do private implementation inheritance. But you can use private interface inheritance.

Private interface inheritance is really just a way to hide methods from a type’s public API. They are compiled into private methods but are actually accessible through a type’s interface map. In other words, they can only be called through a reference typed as the interface on which the method is defined. An example will make this easier to understand:

class PrivateImplementer : IFoo
{
   void IFoo.Foo()
   {
       Console.WriteLine("PrivateImplementer::IFoo.Foo");
   }
}

In this case, PrivateImplementer is publicly known to implement IFoo. Thus, an instance can be treated polymorphically as an instance of IFoo. But you cannot actually call Foo on it unless you do treat it as an IFoo. This code demonstrates this:

PrivateImplementer p = new PrivateImplementer();
p.Foo(); // This line will fail to compile
IFoo f = p;
f.Foo();

You can select individual methods of an interface to implement privately. For instance, if PrivateImplementer implemented IFooBar, it might choose to implement Foo privately, but Bar publicly using the ordinary syntax.

In practice, there aren’t many common cases where you would use private implementation. The System.Collections.Generic library uses this approach to secretly implement all of the legacy System.Collections weakly typed interfaces. This makes backwards compatibility "just work," for example passing an instance of List<T> to a method that expects an IList will work just fine. In this specific example, cluttering the new type APIs would have been a pity (there are quite a few methods necessary for the weakly typed interoperability).

"No," is a pretty poor answer if he was looking to find out what you knew. Sounds like someone who just wants to show how much they know.

afuzzyllama
  • 6,538
  • 5
  • 47
  • 64
Mark Dickinson
  • 6,573
  • 4
  • 29
  • 41
  • 2
    Hi Mark, I saw that Webpage too- isn't that just the same as an explicit interface implementation though? – RichardOD Apr 27 '09 at 10:12
  • 1
    I'm going to +1 this because it is known as private interface inheritance. – annakata Apr 27 '09 at 10:14
  • 6
    That is explicit interface implementation and the interviewer said that was NOT what he meant. – GrahamS Apr 27 '09 at 10:16
  • Not to split hairs, but the question says the interviewer, said "No," when asked if he meant the "difference" between implicit vs explicit interface implementation. Bad interviewers usually mean bad times at the job. – Mark Dickinson Apr 27 '09 at 10:18
  • 6
    True, the answer might simply be that your interviewer was a dick. – GrahamS Apr 27 '09 at 10:22
  • +1; note the last paragraph of the linked post, which explains why you would/wouldn't use it. (Yes, "when would you use x" can appropriately be answered, "in practice, not often.") – John Rudy Apr 27 '09 at 11:09
  • 4
    Which just makes it a terrible, terrible question. "When would you use this obscure technique you've almost certainly not encountered?" Correct answer: Almost never. Incorrect answer: I don't know, I've never used it. I call shenanigans. – annakata Apr 27 '09 at 12:39
2

ShuggyCoUk gives good answer but with such comment

This is a potentially useful case but is not something I would wish to use very often. Certainly it's use in an interview smacks of being a boundary case the interviewer is using because they've seen it and though it was 'interesting'

I, must to say, it's definitely not ability for only smart interviewers.

Here is Realization of Full State Machine (FSM) with inheritance and unitest support, which is good example of private/protected interfaces usage.

It was an answer on questions What is the C# equivalent of friend? and Why does C# not provide the C++ style 'friend' keyword? and, in fact, on your question too.

Community
  • 1
  • 1
max_cn
  • 181
  • 1
  • 5
1

Just like an inner class (which is also private) you can use a private interface in an existing class.

Gerrie Schenck
  • 22,148
  • 20
  • 68
  • 95
1

I googled around a bit and found this article explaining how private interfaces can be used to provide different interfaces to different clients. This is C++ story.

I don't think this can be applied to C# tho, because the same effect IMO can be achieved with explicit interfaces and clients that cast host to appropriate interface.

Maybe somebody else can see something I missed there....

I also found this at MSDN:

Interface methods have public accessibility, which cannot be changed by the implementing type. An internal interface creates a contract that is not intended to be implemented outside the assembly that defines the interface. A public type that implements a method of an internal interface using the virtual modifier allows the method to be overridden by a derived type that is outside the assembly. If a second type in the defining assembly calls the method and expects an internal-only contract, behavior might be compromised when, instead, the overridden method in the outside assembly is executed. This creates a security vulnerability.

majkinetor
  • 8,730
  • 9
  • 54
  • 72