Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a protected property of an internal type in C#?

Tags:

c#

I want InternalClass to be internal (not accessible outside of the assembly)

I also want to define a protected property of type InternalClass (in the same assembly)

This is what I have:

internal class InternalClass 
{
}

Now I want to use this type in another class, however it has to be protected:

public class MyClass
{
   protected internal InternalClass IC { get; }
}

The above code gives me the following error:

Inconsistent accessibility: property type 'InternalClass' is less accessible than property 'MyClass.IC'

When I check the documentation, I can see protected internal is a valid modifier, but I am not sure how to use it?

like image 924
Hooman Bahreini Avatar asked Oct 15 '25 08:10

Hooman Bahreini


1 Answers

The problem is, that MyClass is public, meaning a outside class (one in another assembly) can derive it and then have access to the internal class through the protected internal property. This is because protected internal is protected or internal. From the MS docs:

A protected internal member is accessible from the current assembly or from types that are derived from the containing class.

(emphasis mine)

If you want to keep MyClass public, then you'll need to either make InternalClass not internal, or make the property IC not be accessible from outside by making IC be private protected. From the MS docs:

A private protected member is accessible by types derived from the containing class, but only within its containing assembly

(emphasis mine)

Which seems like what you want.

like image 78
MindSwipe Avatar answered Oct 16 '25 22:10

MindSwipe