What are the ways to declare a class that cannot be instantiated?

11,051

Solution 1

Marking a class as abstract or static (they are mutually exclusive) are the only two ways. Marking all constructors as private does not make the class uninstantiateable since the class can still construct itself, and others might be able to do it via reflection.

Solution 2

Only static looks like complete solution here because abstract class still can be instantiated when class instance that inherits from it is instantiated. Consider the scenario :

abstract class A {  }

class B : A {  } 

somewhere in code :

B instance = new B();  // this creates instance of class A as well

P.S. At first i though that abstract sealed might be solution for this problem as well but it doesn't make much sense to use such a construction so it doesn't even compile :

Error   1   'A': an abstract class cannot be sealed or static   D:\Projects\TEST\Testapp\Program.cs 15  27  ITT.Domain

Solution 3

As answered by others abstract and static classes cannot be instantiated however a class with private constructor can be by using a public member function. This is how the singleton pattern works

Solution 4

internal classes are only visible inside of your assembly and therefore cannot be instantiated outside of this assembly.

But as far as i know, you could still create an instance via reflection. you can disable reflection via ReflectionPermission Class

As mentioned above you could declare it as abstract or add an abstract method.

If you just want to declare a contract, you could use an interface, but that's not a class at all.

sealed means you cannot inherit this class

singleton classes can only be created once per application singleton

see sealed (C# reference)

Share:
11,051
kakkarot
Author by

kakkarot

Updated on June 05, 2022

Comments

  • kakkarot
    kakkarot almost 2 years

    What are the ways to create a non-instantiable class? One way is by declaring it as an abstract class. Is it possible to do it by making the class constructor as private? Is a sealed class, non-instantiable? And, are there any other ways to do it in C#?