InternalsVisibleTo with "private protected"
Asked Answered
L

2

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).

Lifework answered 1/12, 2017 at 10:19 Comment(2)
Good question. I cannot test it either but i assume it will work for private protected too, although they everywhere(f.e. here or here) mention that it applies only to internal members.Morula
Yes that will work as you describe.Zampardi
S
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.

Sensory answered 2/1, 2019 at 16:3 Comment(3)
Citation, please.Commendatory
@RobertHarvey Is there a formal spec for C# 7.2?Sensory
@Sensory even the C# 6 is still a draft. C# development has become fully open, which means features are described in Github proposals in the csharplang repo, debated, prototyped and implemented. The link to the proposal is the best citation, after the Roslyn code itselfLox
C
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)

Carapace answered 9/10, 2019 at 21:21 Comment(1)
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).Prentiss

© 2022 - 2024 — McMap. All rights reserved.