Class protected and public

Asked

Viewed 187 times

4

What is the behavior of a protected class?

What is the impact of access modifiers (especially private and protected) on classes, and what are their common uses?

I can understand its functionality when assigned to methods, properties and attributes, but I can’t see it when it comes to a class or interface.

1 answer

5


A "top-level" class (defined directly in the namespace) cannot be protected - is a build error. You can only define classes protected if they are defined within other classes (such as nested classes). What the modifier does is that only the class itself within which its nested class is defined, or your subclasses, can access your protected class.

For example:

protected class A { } // não compila - erro

public class B {
    protected class C { }
    private void Metodo1() {
        // Funciona
        var c = new C();
        Console.WriteLine(c);
    }
}

public class D {
    private void Metodo2() {
        var c = new C(); // não compila - erro
        Console.WriteLine(c);
    }
}

public class E : B {
    private void Metodo3() {
        // Funciona
        var c = new B.C();
        Console.WriteLine(c);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.