C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,236 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello,
From what I understood, If we use a private constructor in our class, We cannot instantiate from the class. ( We cannot use a new keyword to instantiate)
In the below example, I use instance = new Language(); in the getter and I don't have any error.
public class Language
{
private Language() { }
private static Language instance;
public static Language Instance
{
get
{
if (instance == null)
instance = new Language();
return instance;
}
}
}
Here is how to use a private constructor.
public sealed class Singleton
{
private static readonly Lazy<Singleton> Lazy = new(() => new Singleton());
public static Singleton Instance => Lazy.Value;
public DateTime DateTime { get; set; }
private Singleton()
{
DateTime = DateTime.Now;
}
}
Then to call Singleton.Instance.DateTime
the constructor is only called the first time.
private
means it's only accessible from the current class and your Instance
getter is within the Language
class. If you tried to instantiate Language
from outside of the class you'd get an error.