Protect Class for namespace c#

Asked

Viewed 102 times

4

I am developing a C# application for Unity 3D where it will manage several types of database (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 wanted it to be free use. In java, it was enough to say that it was protected that everything was fine, but that’s not quite how it works from C#. Example in Java:

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
      }
}
  • Error happens because the Mainclass is not in the namespace MDC.

  • The error is what I want to occur in C#, but this does not occur because there is no way I declare a Class as protected.

2 answers

2

I solved the problem as follows. I used the Internal type instead of protected, as I will only make available the library DLL, who will implement it will not be able to instantiate or have access to Internal classes, because only within Assembly will have access to this class. Stayed 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
      }
}
  • 1

    In addition to modifying internal has also the protected internal that its derived classes have access and only within the same Assembly https://msdn.microsoft.com/pt-br/library/ms173121.aspx

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.