Click here to Skip to main content
16,004,727 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i m fresher i m seeking many time from this question in interview
Posted

The only real way to instantiate a private constructor is from inside the class itself. It's common to see this being misused as a way to achieve a singleton pattern by doing something like this:
C#
public class MyFactory
{
  private int _threadCount;
  private static MyFactory _instance;
  private MyFactory()
  {
    _threadCount = 10;
  }
  public static MyFactory Instance
  {
    get
    {
      if (_instance == null)
      {
        // As this belongs to the same object, we can
        // new it up here.
        _instance = new MyFactory();
      }
      return _instance;
    }
  }
}
 
Share this answer
 
I am giving a example that calls method of class that class has private constructor.

1. Create a class that has private constructor

C#
using System;

namespace SingletonExample
{
   public  class User
    {
       private static User user = null;
       private static readonly object padlock = new object();
       private User()
       {
       }

       public static User GetInstance()
       {
           lock (padlock)
           {
               if (user == null)
               {
                   user = new User();
               }
               return user;
           }
       }

       public void GetMessage()
       {
           Console.WriteLine("I am method of class user");
       }

    }
}



2. call the method in execution program

C#
using System;

namespace SingletonExample
{
    class Program
    {
        static void Main(string[] args)
        {
            User user = User.GetInstance();
            user.GetMessage();
            Console.ReadKey();
        }
    }
}


If you want to know more then read this

http://csharpindepth.com/articles/general/singleton.aspx[^]
 
Share this answer
 
See wiki: Singleton Pattern[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900