Class vs. Public Class

What is the difference between:

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

and:

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

So what will be the difference between public class and class?


Solution 1:

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 {}

Solution 2:

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.

Solution 3:

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.