Instantiation With Private Constructor in C# - Singleton Pattern

Shervan360 1,641 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.
11,236 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,471 Reputation points
    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.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. P a u l 10,751 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.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.