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 ?
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With