The C private constructor USES the example

  • 2020-05-30 20:58:05
  • OfStack

Declaring an empty constructor prevents default constructors from being automatically generated. Note that if you do not use an access modifier for the constructor, it remains private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

Sample code:


public class PrivateConClass
{
private static PrivateConClass pcc;
private PrivateConClass()
{
Console.WriteLine("This private constructure function. So you cannot create an instance of this class.");
}
public static PrivateConClass CreatePcc()
{
pcc = new PrivateConClass();
return pcc;
}
public static void ShowStaticMethod()
{
Console.WriteLine("This is a static method. Just be called by Class name.");
}
public void ShowMethod()
{
Console.WriteLine("This is a Nonstatic method. Just be called by private static instance pcc.");
}
}
class Program
{
static void Main(string[] args)
{
PrivateConClass pcc = PrivateConClass.CreatePcc();
pcc.ShowMethod();
PrivateConClass.ShowStaticMethod();
}
}


Related articles: