Search code examples
c#.netmononamespacesencapsulation

Can I break encapsulation/data hiding with namespaces (.Net)


If I am making a .Net dll, is it possible to break encapsulation in any program that uses it, by creating a class with the same namespace?

For example, consider a DLL with the following code in it:

using System;

namespace MyDLL
{
    internal class MyClass
    {
        internal void Stuff()
        {
            ...
        }
    }
}

If I was to then create a project, and reference the DLL, would I be able to do something like the following?

using System;
using MyDLL;

namespace MyDLL
{
    public class TheirClass
    {
        MyClass exposedClass = new MyClass();
        exposedClass.Stuff();
    }
}

I'm currently working on a project that will have a few abstract classes I want a user to be able to inherit, but I only want to certain features to be exposed.

Thanks in advance.


Solution

  • No, using the same namespace have no impact on data encapsulation nor any impact on visibility (private/protected/internal). Namespaces are syntactic sugar in C#, actual class names consist of namespace, name and assembly identity.

    So in your particular case adding class with full name MyDLL.TheirClass{TheirAssembly} will not make MyDLL.MyClass{MyDLL} visible from TheirClass (since your class is internal and new class is from other assembly not marked as InternalsVisibleTo in your assembly).