Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to restrict the class from creating object using constructor

What I have tried:

how to restrict the class from creating object using constructor
Posted
Updated 13-Oct-17 4:37am
Comments
Richard Deeming 13-Oct-17 10:34am    
Unclear what you mean. Are you trying to create a private constructor, that can't be called from outside of the class?

1 solution

Make the constructor private:
C#
public class MyClass
   {
   private static MyClass theInstance = new MyClass();
   private MyClass() {}
   public static MyClass GetInstance()
      {
      return theInstance;
      }
   }
The app can only create a single instance of the class, because the constructor is only available within the class itself.

This is also known as a Singleton pattern.
 
Share this answer
 
v2

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