Static Class In C#

1. What is Static class?

We cannot create instance of static class. It means you cannot use new keyword in static class. Let’s check this in the following code:

Step 1: Create one static class,

Create one static class
Step 2: Try to create instance of static class,

create instance of static class

While you will compile above code it will throw an error like the following:

compile code

So, here we have proved that we cannot create instance of static class.

2. Can we have private, protected, protected internal access modifier for static class?

We cannot have private, protected, protected internal access modifier in static class. Let’s try it with the following code:

static class

Above code will throw the following error: 

code error

Hence, it’s proved that we cannot have private, protected, protected internal modifier in static class.

3. Can we have constructor in static class and how many times it’s called?

We can have static constructor in static class. And it’s called only once.

constructor in static class

4. Can we have access modifier for static constructor?

We cannot have any access modifier for static class constructor. Let’s try to add access modifier to static constructor:

constructor

Above code will throw the following error:

See error

Here we know that we cannot have access modifiers for static constructor.

5. Can we have instance member in static class?

We cannot have instance member in static class. Let us try to add instance method and variable in a static class:

instance member

Above code will throw the following error:

error

Let’s change it to static member and you will observe that I will compile it successfully:

static member

Build

6. Can we inherit static class?

Static class is  sealed by default so we cannot inherit it.


Similar Articles