Create N number of instance of class

Datetime:2016-08-22 22:51:21          Topic: C#  Assembler           Share

Do you know how to create ‘N’ number of instance of class in C#? In my article about the OOP and C# interview question I have asked one of the question (question number 3). Before reading this article you may want to read about the singleton pattern here .

Creating N instance of class

What is the best way to create ‘N’ number of instance of a class. Please check the code below to find the answer.

    public class NumberedInstance
    {
        private static int instanceNumber;
        private NumberedInstance()
        {
 
        }
 
        public static NumberedInstanceGetInstance()
        {
            if(instanceNumber < 5)
            {
                instanceNumber++;
                return new NumberedInstance();
            }
            else
            {
                throw new ArgumentOutOfRangeException("Only five instance of the class are allowed");
            }
        }
    }

As you can see in the above C# code I have created a simple class with private constructor. I can access the public static method named GetInstace(), to get the instance. If the number of instances are more then 5 we will get an exception.

In the above class I have created a class with private constructor. And a static field to keep the number of counts of the instances created.If the count exceeds any specified number an exception is thrown.

Create instance of class for each assembly

If I want to extend this example with an instance for each assembly. I have to write the code as shown below

    public class NumberedInstance
    {
        private static IDictionary<string, NumberedInstance> assemblyInstance= new Dictionary<string, NumberedInstance>();
        private NumberedInstance()
        {
 
        }
 
        public static NumberedInstanceGetInstance(string assemblyName)
        {
            if(!assemblyInstance.Keys.Contains(assemblyName))
            {
                NumberedInstanceinstance = new NumberedInstance();
                assemblyInstance.Add(new KeyValuePair<string, NumberedInstance>(assemblyName, instance));
                return instance;
            }
            else
            {
                return assemblyInstance[assemblyName];
            }
        }
    }

In the above code I have used a dictionary to keep records of all the instances created for the assemblies. If the dictionary already contains the instance. The same instance is returned otherwise a new instance is returned and stored in the dictionary.

In this article I have discussed the ways to create the n instance of a class in C#. And their usage examples.





About List