Search code examples
c#classoopinterface

C# Interfaces and classes. Variables used in the class needed in the interface can't be private, or private only public. Why?


I have a problem with interfaces in C#. I made an interface called IPerson that needs a name and age. After that I created a class that inherits from that interface, so it needs a name and age. When I try to write these variables in the class, they can only be public and I don't understand why.

public interface IPerson
{
    string name { get; set; }
    int age { get; set; }
}

public class Person : IPerson
{
    // If I try to make them private or protected, they don't work. and IPerson will be colored red. Only if they are public it's good, why ?
    private string name { get; set; } 
    private int age { get; set; }
}

Solution

  • An interface is a kind of contract that you state. Everything declared in the interface needs to be accessible in the type that inherits from said interface. When you now declare a method as private, you can't access it from the other object which tries to enact the contract, resulting in the interface not being implemented correctly.

    This is also the reason, why interfaces do not have accessor declarations. The properties, methods and events defined in the interface are required to be public, because otherwise accessing the class instance through the interface would not work.

    In your example, you derive Person from IPerson. Now imagine, you use it like this:

    IPerson c = GetCustomer();
    

    where GetCustomer is defined like this:

    public IPerson GetCustomer() {
        // internal code
    }
    

    All you have access to now, is the given values declared in the interface. This means that name and age are defined in the interface and are accessible.
    Let's say, Person also declares some other properties, like IPerson parent { get; set; }. In this case, the parent may be of type Person or of any other type that inherits from IPerson. But you can always be sure that the object that gets assigned to this property derives from IPerson and will have the properties name and age defined.

    There is also no reason to declare an interface for private members. What would be the benefit your code has from that? Interfaces exist to connect objects that do not know much about the other type, except the interface. Think of it, as a power plug: You plug it into the socket, but it does not care where the power comes from. And likewise, the socket doesn't care where the power is going. It is just the case that both use an interface the other can interact with.
    Using an interface in a class just for itself would be pointless, because there is no information that is hidden or needs to be abstracted within a class.