8

A new version of the .Net framework and C# offer a new access modifier: private protected. In order to access such a member, the class must both

  • reside in the same assembly and
  • derive from the defining class.

(In contrast to protected internal where fulfilling one of the conditions is enough)

For testing purposes, the InternalsVisibleTo attribute comes in very handy when I like to access non-public members of a class from my test class which is in a different assembly.

How does private protected interact with the InternalsVisibleTo attribute? Can I access such member from a class residing in the "friend" assembly which derives from the original class?

(I cannot try that on my machine, because the version of Visual Studio and C# is too old).

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Bernhard Hiller
  • 2,163
  • 2
  • 18
  • 33
  • 1
    Good question. I cannot test it either but i assume it will work for `private protected` too, although they everywhere(f.e. [here](https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx) or [here](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies)) mention that it applies only to `internal` members. – Tim Schmelter Dec 01 '17 at 10:36
  • 1
    Yes that will work as you describe. – Evk Dec 01 '17 at 11:44

2 Answers2

2

Yes, classes in you friendly test-assembly that derives from your base-class will get access to private protected members.

The proposal for the new access modifier is explicit in saying what CLR access specifier it maps to (protectedAndInternal), but does not make any note about how this in turns relates to InternalVisibleTo.

Rune
  • 815
  • 6
  • 17
2

As of now, the documentation for InternalVisibleTo makes mention of both internal and private protected within the Remarks section.

(https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute?view=netcore-2.2#remarks)

digitlworld
  • 1,046
  • 7
  • 13
  • In the link you provided it says: "This applies only to internal (Friend in Visual Basic), protected internal (Protected Friend in Visual Basic), and private protected (Private Protected in Visual Basic) members, but not private ones." So emphasize that it's **protected internal**, not protected (same for private). – Sagi Sulimani Apr 30 '23 at 08:11