Create N number of instance of C# class

By | August 10, 2016

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.

Become an Expert in Programming and Web Development.View all courses!

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.

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

 

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.