Is there an access modifier that limits to a solution?

c# .net access-modifiers

602 просмотра

4 ответа

In my .NET solution, I have two projects: one main project and a project for running tests against the main project. In my project, I have several methods that I'd like to keep "private", but would also like to run tests for. Is there an access method that could limit these functions to just inside of my solution?

Автор: Kevin Evans Источник Размещён: 13.11.2019 11:48

Ответы (4)

6 плюса


You are looking for the InternalsVisibleTo attribute.

This attributes lets you specify other assemblies that should have access to types and methods that are internal to your assembly. So, in your main project AssemblyInfo.cs file (or any other source file), you can specify that your test project is a 'friend assembly' and should have access to the internals of your main project:


On a side note, as pointed out by Alexei, if your MainProject is signed with a strong name key, any 'friend' assembly must also be signed. This is explained here

Although, as mentioned in another comment. Best practice is to test your assembly by using its public API.

Автор: lenkan Размещён: 07.12.2015 04:52

2 плюса

You can use InternalsVisibleTo attribute to make internal types and methods visible to selected assemblies.

However, you should try to design your API so that it can be tested using only the public interface.

Автор: Jakub Lortz Размещён: 07.12.2015 04:54

2 плюса

You should seriously think back about the architecture of your solution. This is a smell that often shows that your class does too much things at once.

A simple fix is to extract this responsibility (those private methods) to another class where they then become public and are testable out of the box...

Автор: Tim Bourguignon Размещён: 07.12.2015 04:55

1 плюс

No, there is no way to limit access to "just solution".

The reason is solution is simply group of projects. One project can be in any number of solutions. So even if you "limit" access to projects included in one solution you/someone else can create another solution that somehow will need to magically get access to methods.

Additionally built assembly does not include any information on what solution it was part of - so there is no information at run time to check access.

To you particular problem - InternalsVisibleTo (as shown in other answers) will give access to internal methods to projects you allow (requires strongly signed assemblies) or refactor your code to avoid need for testing private methods.

Автор: Alexei Levenkov Размещён: 07.12.2015 05:02
Вопросы из категории :