Someone ask me that do we make an object of class having private constructor
for E.g
Class Parent
{
Private Parent()
{
}
}
Since i made a private constructor for class Parent.so it is obvious that we can't make object of Parent class.but is there is a way to make Parent class object without changing the private constructor into public?
Thanks in Advance
You can't create an instance of Parent
outside that class, but:
Parent
if they're nested classes within Parent, and those could have non-private constructed.Code (including static methods, most commonly) within the Parent
type can create instances of Parent
so you might have a static factory method, but not expose any constructors directly. For example:
public class Parent
{
private Parent {}
public static Parent CreateParent()
{
return new Parent();
}
}
It can sometimes be useful to have this sort of approach, if you want to apply argument validation (etc) before creating an instance of a type, and you therefore want to force everything through named factory methods. That can also make code easier to read, particularly if you want to have different ways of creating an instance from the same number of values. TimeSpan.FromSeconds
, TimeSpan.FromMinutes
etc are good examples of this.