Make All Constructors Private to Prevent Object Creation

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.
1
2
3
4
5
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 theDog class, it has access to the private constructor.
1
2
3
4
5
6
7
8
9
10
11
12
13
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.