Is such a design possible? I want multiple classes to be able to communicate freely between each other, but not be accessible from outside of that group. A namespace that the user can’t register to, even if they wanted.
On top of that, there’s an additional constraint. I need to have at least one public entry point to the group of classes.
Right now, I was thinking about nesting the classes, but there’s quite a few. It will get messy.
Technically speaking .net can always be reflected, so though you can restrict things… they can always reflect out the inner guts. So what I describe is more a “restrict as a practice” rather than “restrict as a security”. So if you’re attempting to “protect” internal code, this won’t work… but if you want to just impress upon your users how the API should be accessed… yeah, there’s a way.
private and internal
If you create your own library, anything you mark internal will only be directly accessible inside that library. Anything public is allowed outside. (same goes for private, where private is inside a given class, rather than library)
Mind you this is “library” and not “namespace”. If you distribute your code as a unity package that just drops *.cs files into your project… even though it may have its own namespace doesn’t mean it’ll be its own library. It’ll get compiled into the primary code library of the Unity project and will be accessible as internal to that library.
But if you compile it into its own dll that is then distributed to the user… then it’s its own library.
Thank you, it is the perfect solution to my problem. It works wonders.
For anyone who stumbles upon thread, here’s the test I ended up running. I created a project and imported Unity’s CoreModule DLL as a dependency. Then I compiled this into a DLL.
using UnityEngine;
public class OpenClass
{
public void DoStuff()
{
RestrictedClass restrictedClass = new RestrictedClass();
restrictedClass.DoStuff();
}
}
internal class RestrictedClass
{
public void DoStuff()
{
Debug.Log("Hello World");
}
}
Then I imported the DLL into a fresh project, and as expected, I can’t make the call to restricted class but I can do this:
using UnityEngine;
public class Test : MonoBehaviour
{
private void Start()
{
OpenClass openClass = new OpenClass();
openClass.DoStuff();
}
}
You can achieve the same thing with assembly definition files. It’s going to involve longer compile and reload times than with a dll, but you can edit the files without having to rebuild the dll.
Yeah, I should have mentioned assembly definition files… unfortunately I don’t have a lot of extensive experience with them personally so I forgot to mention them.