Class vs. Public Class

前端 未结 3 1490
一个人的身影
一个人的身影 2020-12-23 11:28

What is the difference between:

namespace Library{
    class File{
        //code inside it
   }
}

and:

namespace Library{
         


        
相关标签:
3条回答
  • 2020-12-23 11:47

    By default, all classes (and all types for that matter) are internal, so in order for them to be accessible from the outside (sans stuff like InternalsVisibleToAttribute) you have to make them public explicitly.

    0 讨论(0)
  • 2020-12-23 11:52

    Without specifying public the class is implicitly internal. This means that the class is only visible inside the same assembly. When you specify public, the class is visible outside the assembly.

    It is also allowed to specify the internal modifier explicitly:

    internal class Foo {}
    
    0 讨论(0)
  • 2020-12-23 11:53

    The former is equivalent to:

    namespace Library{
        internal class File{
            //code inside it
       }
    }
    

    All visibilities default to the least visible possible - private for members of classes and structs (methods, properties, fields, nested classes and nested enums) and internal for direct members of namespaces, because they can't be private.

    internal means other code in the same assembly can see it, but nothing else (barring friend assemblies and the use of reflection).

    This makes sense for two reasons:

    1. You should be consciously making things use the least visibility possible anyway, to strengthen your encapsulation.
    2. If they defaulted to public you could accidentally make something public that should be private or internal. If you accidentally make something not visible enough, you get an obvious compile error and fix it. If you accidentally make something too visible you introduce a flaw to your code that won't be flagged as an error, and which will be a breaking change to fix later.

    It's often considered better style to be explicit with your access modifiers, to be clearer in the code, just what is going on.

    0 讨论(0)
提交回复
热议问题