0

I have two namespaces:

namespace MyNamespace

and

namespace MyNamespace.Test

the second one is for Unit Testing. I don't want to make the classes within "MyNamespace" public but I want the unit tests to be able to access them. I tried internal because from the Access Modifier documentation I had assumed that "MyNamespace.test" would be derived but it's not working. Do I use a different access modifier or is my namespace wrong?

Trevor Vance
  • 321
  • 2
  • 11

1 Answers1

1

Namespaces have no bearing on accessibility / visibility in C#; they are simply prefixes to type names to enable grouping of similar types together, for use with things like using statements. It's essentially a compile-time concept, the runtime doesn't recognize namespaces as logical entities and requires fully-qualified names in the compiled code.

Instead, access is done on a per-assembly basis. An assembly is the .dll or .exe file each C# project produces. The same namespace may appear in multiple assemblies, and multiple namespaces may appear in the same assembly.

Marking something internal means "allow access to it from anywhere in the same assembly as where this thing is declared". So if your unit tests are in a different assembly (as they should be, unless you want to ship your unit tests to customers!), they won't be able to access types in the MyNamespace, regardless of what namespace the tests are declared in.

However, you can have your product assemblies allow an exception to this rule with the InternalsVisibleTo attribute. See this answer for details.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34