Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class vs. Public Class

Tags:

c#

public

class

People also ask

What is a public class?

In object-oriented programming, a public class is any part of the program that accesses or updates its members using the member name to be accessed. This type of class is useful for information or methods that need to be available in any part of the program code. Class, Private, Programming terms.

What is the difference between public class and class in C#?

In C#, a class by default has internal access (i.e. this class is only visible within the assembly). A public class will have access in the assembly it is part of and all other assemblies where it is referenced.

What is the difference between a public and a non public class?

A public class will have access specifier "public" and its members can be accessed with in and out of the class in which they are specified. A class which doesnt have the public access specifier are called as non-public classes and its member can be accessed only within the class in which they are specified.


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

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.


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.