Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Team,

I want to restrict user from creating more than 1 object . I know this concept in singleton concept. However I am trying to achieve in the following way.

If you observe the below program i am throwing exception inside the "if loop" if i dont throw the exception inside the "If" loop object gets created and i will be able to access the method using the third object i.e ex3.Display(); Can some one help me how to handle the exception at same time object does not get created

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectCreation
{
    class ExampleClass
    {
        public static int classCount = 0;

        public ExampleClass()
        {
            classCount++;

            if (classCount > 2)
            {
                throw new Exception("Object creation failed - object creation limited only for one");

            }

            else
            {
                Console.WriteLine("Object Created" + classCount);
            }
        }

        public void Display()
        {
            Console.WriteLine("object created");
        }


    }

    class Program
    {


        static void Main(string[] args)
        {

            ExampleClass ex1 = new ExampleClass();
            ExampleClass ex2 = new ExampleClass();
            ExampleClass ex3 = new ExampleClass();
            ex3.Display();

        }
    }
}
Posted
Comments
James_Parsons 20-Aug-15 21:49pm    
Shouldn't `classCount` be `private`?
ShaHam11 20-Aug-15 21:52pm    
yes, I have made it has private but still does not solve my issue.
Sergey Alexandrovich Kryukov 20-Aug-15 22:51pm    
"classCount"? There is only one class anyway. Instance count? But you want only one. This is absurd. No, this is not a reasonable implementation.
—SA
PIEBALDconsult 31-Aug-15 22:47pm    
As SA pointed out, you are trying for the Singleton Pattern, one of the very worst Design Patterns and best avoided.

"restrict user from creating"
Users don't create. Developers create. You are the developer. Do you not trust yourself to create only one?

1 solution

Please see my comment to the question. Don't worry: there are many bad implementations of the pattern. It's generally trivial, but there are some delicate moments to take into account which require thorough considerations. Want to see a good one? Here: http://csharpindepth.com/Articles/General/Singleton.aspx[^].

—SA
 
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