Beta033
Beta033

Reputation: 2013

ERROR: the accessibility modifier of the set accessor must be more restrictive than the property or indexer

i'm having a bit of confusion with property accessors.

I'd like to have an internal property with its set accessor only accessible to derived classes.

something like this

internal [internalClass] MyProperty
{
get {return _prop;}
protected set {_prop = value;}
}

when i do this the compiler complains.

MSDN, when discussing this particular error suggests changing the set access modifier to private

which is not where i want this to go.

it looks like Protected Internal should be an option here however using this modifier gives the same error

I have a feeling i'm missing some basic understanding of access modifiers.

thanks

Upvotes: 8

Views: 5754

Answers (3)

dthorpe
dthorpe

Reputation: 36082

Internal is more restrictive than protected. Internal makes the member limited to the current assembly, whereas protected is accessible to an arbitrary large number of descendants outside of your assembly.

If you intend for this property to be accessible to classes or descendants outside of your assembly, you'll need to lose the internal attribute on the property. If you intend for this property to be used only within your assembly, then make the property accessor internal.

Unfortunately, this means you have to give up protected on the accessor of internal properties. This is an irritation because even though the property is limited to clients within your assembly, that doesn't mean you really trust all those clients to use your property correctly. It makes sense when you are the only author running around in your assembly's source code, but I would much prefer to retain protected semantics on internal classes when there are hundreds of developers running around in the source code of one large assembly.

Upvotes: 2

TreDubZedd
TreDubZedd

Reputation: 2556

For whatever reason, the compiler seems to believe that an internal class is permitted to have derived classes in other assemblies. The protected field is then considered available to other assemblies, through the derived class (that is, the field has no concept on its own of its class's access modifier). The compiler error is to indicate that (even though you know it won't ever happen) the indicated field is overextending its access rights.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502016

Neither protected nor protected internal is more restrictive than internal. Both would let derived types from a different assembly access the setter but not the getter. protected internal gives access to the union of protected and internal, not the intersection. (There is an access level representing the intersection in the CLR, but it's not exposed by C#.)

You might be best off using a private setter and a protected SetMyProperty method which just calls the private setter, if that matches what you want to achieve.

Upvotes: 12

Related Questions