Reputation: 414
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?
Upvotes: 2
Views: 1749
Reputation: 28499
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://learn.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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected
Upvotes: 2
Reputation: 190907
You could create an internal method (or a proxy property) to call set on it.
protected int Foo { private set; get; }
internal void SetFoo(int foo)
{
Foo = foo;
}
In this case you can set the setter of Foo
to private
.
Do note that this allows anything in your assembly that has a reference to this object can call SetFoo
, which may not be what you want.
Upvotes: 5