Class vs. Public Class

C#ClassPublic

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1678541View Question on Stackoverflow
Solution 1 - C#driisView Answer on Stackoverflow
Solution 2 - C#Jon HannaView Answer on Stackoverflow
Solution 3 - C#Anton GogolevView Answer on Stackoverflow