#293 – You Can Declare a Private Constructor
April 6, 2011 Leave a comment
It’s possible to have one or more instance constructors be private. A private constructor means that only code internal to the class can construct an instance using that particular combination of parameters.
Below is an example, where we have a public Dog constructor that takes two arguments, but a private one that takes only a name.
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
private Dog(string name)
{
Name = name;
}
A private constructor is typically called from within a static method in the class. For example:
public static Dog MakeAnOldDog()
{
// Use private constructor
Dog oldDog = new Dog("Rasputin");
oldDog.Age = 15;
return oldDog;
}