#294 – Make All Constructors Private to Prevent Object Creation
April 7, 2011 Leave a comment
If you want to prevent code external to a class from creating instances of that class, you can make all of the constructors of the class private.
In the following example, we have a single Dog constructor, which is private.
private Dog(string name, int age) { Name = name; Age = age; }
Because the constructor is private, code outside the Dog class cannot create a new instance of a Dog.
But we can have a static method in the Dog class that can create instances. Because the code is defined inside the Dog class, it has access to the private constructor.
public class Dog { // code omitted public static Dog MakeADog() { // Use private constructor Dog nextDog = new Dog(nameList[nextDogIndex], ageList[nextDogIndex]); nextDogIndex = (nextDogIndex == (nameList.Length - 1)) ? 0 : nextDogIndex++; return nextDog; }
Now if we want a new Dog instance, we can call the MakeADog method.