Instantiation With Private Constructor in C# - Singleton Pattern

Shervan360 1,011 Reputation points
2023-01-15T11:30:08.37+00:00

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;
            }
        }
    }
C#
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.
6,953 questions
No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 29,236 Reputation points Microsoft MVP
    2023-01-15T17:44:51.5833333+00:00

    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.

    No comments

1 additional answer

Sort by: Most helpful
  1. P a u l 7,566 Reputation points
    2023-01-15T12:00:59.22+00:00

    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.

    No comments