Property with internal set and protected get

I want to do so a variable (let’s call it Foo) that can only be modified within the assembly but can be acessed by any child class, even outside the assembly So I want to have an internal set and a protected get:

Doing protected int Foo { internal set; get; } tells me this that the set must be more restrictive than the property or indexer But internal int Foo { set; protected get; } tells me the same thing for the get

How can I solve that?

Answer

Use internal for the setter and protected internal for the whole property.

public class X
{
    // Read from this assembly OR child classes
    // Write from this assembly
    protected internal int Foo { internal set; get; }

}

The name protected internal is a bit misleading, but does what you want to achieve:

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

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected-internal

So, because the setter is internal, you can set the property from anywhere in the same assembly but not from a different assembly. And because the property as a whole is protected internal, you can read it from anywhere in the same assembly OR from child classes in any assembly.


Another approach:

public class X
{
    // Read from child classes 
    // Write only from child classes in the same assembly
    protected int Foo { private protected set;  get; }

}

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

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected