Class versus Public Class

What's 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 an open class and a class ?

+47
public c # class
Sep 12
source share
3 answers

Without specifying public class is implicitly internal . This means that the class is displayed only within one assembly. When you specify public , the class will be visible outside the assembly.

It is also allowed to explicitly specify the internal modifier:

 internal class Foo {} 
+51
Sep 12
source share
— -

The first is equivalent to:

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

All default visibilities for the least visible are private for class es and struct members (methods, properties, fields, nested classes and nested enum s) and internal for direct namespace s members, because they cannot be private.

internal means that other code in the same assembly can see it, but nothing else (forbidding assembly of nodes and using reflection).

This makes sense for two reasons:

  • You must consciously force things to use the least visibility anyway in order to strengthen your encapsulation.
  • If they do not match public by default, you can accidentally do something public, which should be private or internal. If you accidentally make something insufficiently visible, you will get an obvious compilation error and fix it. If you accidentally make something too visible, you introduce a flaw in your code, which will not be flagged as an error, and which will be changed later to fix it.

It is often believed that the best style should be explicit with your access modifiers in order to be clearer in the code, only what happens.

+19
Sep 12 '12 at 16:55
source share

By default, all class es (and all types in this case) are internal , so in order for them to be accessible externally (without things like InternalsVisibleToAttribute ), you must make them public explicitly.

+1
Sep 12
source share



All Articles