Default Scope of a C# Class

Introduction

One of my favorite interview questions I ask is "what is the default scope of a C # class?". What do you think?

Many times people answer, that it is either private or public. So let me correct that first. In C# a class can't be declared as private, let's try to do so; see.

Default-Scope-of-Csharp-Class1.jpg

This clearly demonstrates that a C# can't even be either protected or protected internal.

So you have two choices left now, a C# class's scope can be either public or internal.

Now, the class design best practices doesn't allow a class to be promoted to public, unless there is a business case. In other words this class is serving other classes or its functionality is being re-used by other classes etcetera.

So, now there is only one choice left, and that is of course "internal", and so that is what we use. In other words the default scope of a C# class is internal.

Let's not just cram or remember this, get into the details and see it yourself.

Procedure to demonstrate Default Scope of C# Class

  1. Be in the project where your class is available.
  2. Go to the view menu and select "Object Browser
    " Default-Scope-of-Csharp-Class2.jpg
  3. This will open a window as shown here; observe that projects are listed in alphabetical order and so our project ClassLibrary1 appears first.
    Default-Scope-of-Csharp-Class3.jpg
  4. Expand the ClassLibrary1 node, as shown here.
    Default-Scope-of-Csharp-Class4.jpg
  5. Now select the Class1 and see the details pane on the right hand side.
    Default-Scope-of-Csharp-Class5.jpg
    Observe that the default scope of C# class is internal.

How to make a Class Private?

C# doesn't allow doing so, as you have seen in the first image above. But a nested type can be private, protected or even protected internal.

Default-Scope-of-Csharp-Class6.jpg

Summary

This article has not onlyexplained the default scope, but also explained how to see such details behind the scenes in Visual Studio.


Similar Articles