andreister
andreister

Reputation: 13871

Fine-grained visibility for 'internal' members

Recently I was reading about partitioning code with .NET assemblies and stumbled upon a nice suggestion from this post: "reduce the number of your .NET assemblies to the strict minimum".

I couldn't agree more! And one of the reasons I personally see most often, is that people just want to isolate some piece of code, so they make the types/methods internal and put them into a separate project.

There are many other reasons (valid and not) for splitting code into several assemblies, but if you want to isolate components/APIs while still having them located in one library, how can you do that?

namespace MyAssembly.SomeApiInternals
{
     //Methods from this class should not 
     //be used outside MyAssembly.SomeApiInternals
     internal class Foo
     {              
          internal void Boo() { }
     }
}

namespace MyAssembly.AnotherPart
{
     public class Program
     {              
          public void Test() 
          {
               var foo = MyAssembly.SomeApiInternals.Foo();
               foo.Boo(); //Ok, not a compiler error but some red flag at least 
          }
     }
}             

How can one restrict a type/method from being used by other types/methods in the same assembly but outside this very namespace?

(I'm going to give a few answers myself and see how people would vote.)

Thanks!

Upvotes: 3

Views: 148

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292405

You could put the code in different assemblies, then merge the assemblies with ILMerge in a post-build step...

Upvotes: 3

Ruben Bartelink
Ruben Bartelink

Reputation: 61795

Use NDepend and put in CQL rules that embody what you want and run them as part of your build. The language isnt interested in this level of restrictions. (I hadnt followed your link yet - are you really trying to do this without NDepend? Your answer should rule it in or out)

Upvotes: 2

Related Questions