Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the "protected" and "protected internal" modifiers in .NET?

What is the difference between the "protected" and "protected internal" modifiers in .NET?

like image 736
Bhaskar Avatar asked Dec 01 '22 12:12

Bhaskar


2 Answers

private

Access is only allowed from within a specific type

protected

private access is expanded to include inheriting types

internal

private access is expanded to include other types in the same assembly

And so it follows that:

protected internal

private access is expanded to allow access for types that either inherit from or are in the same assembly as this type, or both.

Basically, think of everything as private first, and anything else you see as expanding on that.

like image 189
Joel Coehoorn Avatar answered Dec 10 '22 05:12

Joel Coehoorn


protected

Members are only visible to inheriting types.

protected internal

Members are only visible to inheriting types and also to all types that are also contained within the same assembly as the declaring type.

Here is a C# example:

class Program
{
    static void Main()
    {
        Foo foo = new Foo();

        // Notice I can call this method here because
        // the Foo type is within the same assembly
        // and the method is marked as "protected internal".
        foo.ProtectedInternalMethod();

        // The line below does not compile because
        // I cannot access a "protected" method.
        foo.ProtectedMethod();
    }
}

class Foo
{
    // This method is only visible to any type 
    // that inherits from "Foo"
    protected void ProtectedMethod() { }

    // This method is visible to any type that inherits
    // from "Foo" as well as all other types compiled in
    // this assembly (notably "Program" above).
    protected internal void ProtectedInternalMethod() { }
}
like image 38
Andrew Hare Avatar answered Dec 10 '22 06:12

Andrew Hare