C# - Static class,Private Constructor,abstract class - all prevent instance creation-which one to use?
c#
Solution
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).
Problem
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 ?