Protect Class for C # namespace

4
I'm developing a C # application for Unity 3D where it will manage various database types (Mysql, Postgress ...), the problem is that I have classes that manipulate each type of database within my namespace, which are used by several other classes, the problem that these classes do not want to be instantiated outside my namespace, but inside I wanted it to be free to use. In Java, suffice to say that it was protected that everything was fine, but that's not how it works in C #. Java Example:

namespace MDC {
    protected class Mysql {
         public Mysql(){}
    }

    public class Database {
         public Database(){
               new Mysql(); // Sucesso
         }
    }
}

public class MainClass {
      public static void Main (string[] args) {
            new Database(); // Sucesso
            new Mysql(); // Erro
      }
}
    
asked by anonymous 30.05.2016 / 23:15

2 answers

2

I solved the problem as follows. I use the Internal type instead of protected, as I will only make DLL available to the library, whoever implements it will not be able to instantiate or have access to Internal classes, because only inside the assembly will have access to this class. It looks like this:

namespace MDC {
    internal class Mysql {
         public Mysql(){}
    }

    public class Database {
         public Database(){
               new Mysql(); // Sucesso
         }
    }
}

public class MainClass {
      public static void Main (string[] args) {
            new Database(); // Sucesso
            new Mysql(); // Erro
      }
}
    
31.05.2016 / 02:08
1

Use the private modifier if you want the class to be visible to different assemblies , use internal .

    
31.05.2016 / 02:09