Hi,
Can we create an object of a class having private constructor. If so, then how? Please tell me.
Thanks in advance
Printable View
Hi,
Can we create an object of a class having private constructor. If so, then how? Please tell me.
Thanks in advance
I would think that if the constructor is private, then no non-member could access the constructor. However, class members including static members would still be able to do so.
so one might build a class such as the following...
and call it as follows ...Code:public partial class xyz {
public string abc;
public int number;
private xyz() {
abc = "this is a public string";
number = 7;
}
public static xyz pleaseConstructAnObjectForMe() {
return new xyz();
}// end function 'pleaseConstructAnObjectForMe'
}// end this segment, class 'xyz' partial declaration
indeed, I may be mistaken, but I seem to recall seeing instances in the .NET Framework where classes couldn't be constructed other than by referencing a static function.Code:// xyz pXYZ = new xyz(); // doesn't compile!
xyz pXYZ = xyz.pleaseConstructAnObjectForMe();
MessageBox.Show(pXYZ.abc);
OldFool