1.

How to declare a private constructor in C#?

Answer»

In C#, if you don’t specify any access specifier against a constructor, that constructor is by default specified as a public constructor by the compiler.

If you want to create a Private constructor explicitly, it can be declared in C# with the help of a private keyword placed before the constructor name in its signature, as shown below:

private constructor_name
{
// Code
}

However, to create an instance of a class with a private constructor is a tricky thing. To do so, the Singleton class is used. Singleton class is a class that has only one instance. Below is the example to create an instance of a class with a private constructor, with the help of the Singleton class.

using System;
public class SingletonDemo
{
private static string CreatedOn;
private static SingletonDemo instance = null;

private SingletonDemo()
{
CreatedOn = DateTime.Now.ToLongTimeString();
}

public static SingletonDemo getInstance()
{
if (instance == null)
{
instance = new SingletonDemo();
}
Console.WriteLine(CreatedOn);
return instance;
}
}


Discussion

No Comment Found