Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is internal protected not more restrictive than internal?

I'd like to create an internal auto-property:

internal bool IP { get; protected internal set; } 

I thought it would be possible to make the setter protected or protected internal - but I always get the error accessibility modifier must be more restrictive than the property. Isn't that the case? Private does not help me, here.

EDIT:
The question is: How do I implement an auto-property with a internal getter and a protected setter?

like image 814
tanascius Avatar asked Jun 30 '09 14:06

tanascius


People also ask

What is the difference between internal and protected?

protected: The type or member can be accessed only by code in the same class , or in a class that is derived from that class . internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.

What is protected internal access modifier?

The protected internal keyword combination is a member access modifier. A protected internal member is accessible from the current assembly or from types that are derived from the containing class. For a comparison of protected internal with the other access modifiers, see Accessibility Levels.

What is private and public in C#?

public. The code is accessible for all classes. private. The code is only accessible within the same class.


2 Answers

It's effectively protected or internal, not and. It's accessible both by derived classes and types in the same assembly. It's a common misconception to think protected internal means accessible only to derived classes in the same assembly.

like image 94
mmx Avatar answered Sep 28 '22 17:09

mmx


At the .NET level, there are two similar but distinct access levels:

  • FamilyAndAssembly: more restrictive than either protected or internal
  • FamilyOrAssembly: less restrictive than either protected or internal

"protected internal" in C# means FamilyOrAssembly; there's no modifier for FamilyAndAssembly.

So, your protected internal setter is less restrictive than the internal overall property. What you could do is:

protected internal bool IP { internal get; set; } 

But then your setter is less restricted than your getter, which is odd...

Another (somewhat equivalent) alternative is:

internal bool IP { get; set; }  protected void SetIP(bool ip) {     this.IP = ip; } 
like image 20
Jon Skeet Avatar answered Sep 28 '22 15:09

Jon Skeet