Is there a more detailed explanation of the class access control syntax in C# using the assembly-level attribute [InternalsVisibleTo]?

wu sheng 20 Reputation points
2023-11-19T12:51:27.8433333+00:00

Please look at the original text in the book below. I have read about the access control modifiers in C#, such as public, private, etc. However, I couldn’t find in the book the syntax for further control through (IExtensionManager extentionMgr). Where can I find an introduction to this syntax? What keywords should I use to search?

Additional information: IExtensionManager is an interface used in LogAnalyzer.


If you dislike adding a public constructor that everyone can see to your class, you can make it internal instead of public. You can then expose all internal related members and methods to your test assembly by using the [InternalsVisibleTo] assemblylevel attribute. The next listing shows this more clearly.

public class LogAnalyzer
{
...
internal LogAnalyzer (IExtensionManager extentionMgr)
{
manager = extentionMgr;
}
...
}

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,845 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,922 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,731 Reputation points
    2023-11-19T14:26:31.22+00:00

    Have you read through the official documentation of InternalsVisibleTo?:

    https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute?view=net-8.0#remarks

    In your example you've defined the LogAnalyzer class with an internal constructor. That means that this constructor is only visible within the defining assembly.

    If you wanted to make this constructor visible to another assembly (e.g. OtherAssembly) then you'd define an assembly-level attribute anywhere in the assembly that defines LogAnalyzer like this:

    [assembly:InternalsVisibleTo("OtherAssembly")]
    

    The most common scenario for this that I've seen is when you have a test project that you want to expose some internals to in order to setup context in such a way that it can be tested.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.