Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control class visibility by owner in c#

Often I want some (or all) functions of some class C1 to be accessible only from within another class C2, because C2 is kind of a proxy, it owns objects of type C1 (e.g.: methods of a class "Neuron", like "connect()", should only be accessible from "Brain"). I assume this is not directly possible with C# unlike with inheritance, where we can specify visibility with a keyword like "private" or "protected".

What is the best practice in such a situation?

like image 419
Yekoor Avatar asked Feb 18 '23 01:02

Yekoor


2 Answers

Create an assembly for your classes and declare the internal class that should not be visible to the outside world as internal:

internal (C# Reference):

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly

So, something like this:

namespace YourAssembly.Classes
{
    internal class C1
    {
        public void Foo()
        {
        
        }
    }
    
    public class C2
    {
        public void DoFoo()
        {
            new C1().Foo();     
        }
    }
}

Here C2 is accessible from other assemblies, while C1 can only be accessed from within the same assembly.

like image 119
CodeCaster Avatar answered Feb 20 '23 15:02

CodeCaster


If C1 cannot be accessed by anybody but C2, then make C1 a private class of C2.

public class C2
{
    public C2() { }

    private class C1
    {
        public C1() { }
    }
}

However, if C1 can be accessed outside of C2, then you're going to need to pass in some kind of key into the ctor of C2 to ensure it's a trusted proxy.

public class C1
{
    public C1(string key)
    {
        // verify that it's a valid proxy or user of this class via the key
    }
}
like image 45
Mike Perrenoud Avatar answered Feb 20 '23 14:02

Mike Perrenoud