Search code examples
c#visual-studiocompile-time

In C#, how to restrict who can call a method at compile time


In C#, is it possible to restrict who can call a method at compile time?

I've looked into directives, but that didn't work since I can't assign values to symbols.

#define WHO VisualStudioUser.Current // does not work

I also looked into Code Access Security (CAS) but that's runtime enforcement, not compile time.

The requirement is to restrict access to a method at compile time for specific developers given the method exists in a pre-compiled assembly.

here's more details... I'm building a framework or a series or assemblies for a team of developers. Because of our software license restrictions, I can only allow a few developers to write code to make a call to some restricted methods. The developers will not have access to the source code of the framework but they'll have access to the compiled framework assemblies.


Solution

  • The requirement is to restrict access to a method at compile time for specific developers given the method exists in a pre-compiled assembly.

    One way is to mark the method private or internal, it won't be callable by anyone outside the assembly. UPDATE: Also take a look at the InternalsVisibleTo attribute, which is used to define which assemblies can "see" internals of your assembly.

    Another way is to divide the code you want to distribute from the code you don't want people to call into separate assemblies. Maybe you just share an assembly mostly of interfaces with your users, that they them compile against; and you have a separate assembly with implementations that they shouldn't reference directly. Your internal team would have access to the implementation assembly. This is just a common form of dependency management, the dependency inversion principle.