Search code examples
c#projectaccess-modifiersproject-reference

Making functions accessible from other classes in same project but not in another Project


I have a project called Category_Helper_Project.

Within this project are two relevant classes: Category_Interface and Category_File_Manager

The purpose of this project is that it can be referenced from other projects. It handles the underlying file system automatically when creating/accessing categories.

To do that, class Category_Interface accesses class Category_File_Manager. Functions in Category_File_Manager are public for this reason.

If I reference Category_Helper_Project from another Project, is it possible to make Category_File_Manager inaccessible from the other project whilst keeping it accessible from Category_Interface? Accessing Category_File_Manager` directly most likely causes problems in the tree structure.

Lastly I would like to know if making Category_File_Manager inaccessible will also make it inaccessible in unit tests, which would be quite unfortunate.

I have found some simmilar questions such as Making a function only accessible from one other function but they didnt really answer my questions.


Solution

  • To control class accessibility you have a keyword you add before its declaration:

    public class Category_File_Manager 
    

    If you do not add the public it defaults to internal and that would result in class being accessible from project/library that declares it and not accessible from any other, that includes tests.

    You can circumvent this using InternalsVisibleTo assembly level attribute for test library benefit.

    [assembly: InternalsVisibleToAttribute("Category_Helper_Project_Tests")]
    

    This has a bit of a code smell that your library becomes somewhat aware of the test library but this is a case of having a cake and eating it. It is a good idea to remove such access from production code so I would wrap this in compilation if so it is not added on release build.

    #if DEBUG
    [assembly: InternalsVisibleToAttribute("Category_Helper_Project_Tests")]
    #endif