Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...