#294 – 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.

        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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: