Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Static class,Private Constructor,abstract class - all prevent instance creation-which one to use?

Tags:

c#

I am bit confused in the usage of Static class, Private constructor and abstract class

to prevent instance creation.( Confused about the alternatives).

What is the scenario that fit the best for each ?

like image 686
user160677 Avatar asked Feb 06 '26 00:02

user160677


2 Answers

That depends on your needs.

  • Static class may be considered "a bunch of methods" - you would use it, if you just need to group some methods, sample usage: MathHelpers, with methods like Sin, Cos, ConvertXToY (or to host extension methods).

  • Private constructor - this one you would use, when you want to be able to control how the object is created, for example, if you want to make sure, that those objects can only be created by your static methods. An example:


class Robot
{
 public string Name { get; }
 private Robot() 
 { 
   // some code
 }

 public static Robot CreateAndInitRobot(string name)
 {
   Robot r = new Robot();
   r.Name = name;
   return r;
 }
}
  • Abstract classes - Those you should use, when you are defining some abstract object, that shouldn't been initialized, because it's incomplete / abstract, and you want to further specialize it (by inheriting from it).
like image 184
Marcin Deptuła Avatar answered Feb 07 '26 14:02

Marcin Deptuła


You use a static class when you only have static members. It doesn't work for any scenario when you want to inherit the class.

A private constructor ensures that only code inside the class itself can create instances of it, i.e. a static method or an instance method in an already existing instance. Even if you inherit from the class, it still has to call the creation process of the base class, so there is no way around it.

An abstract class is useless for preventing instance creation. You have to inherit the class to use it for anything, and you can add whatever constructor you like to the descendant class.

like image 37
Guffa Avatar answered Feb 07 '26 13:02

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!