Introduction
In this blog, I am going to explain how to find the number of objects or instances that are created of a class, using C# . Thus, In my blog, I am going to solve this scenario in two ways.
  • Without using the inbuilt functionality in C#
  • Using the inbuilt functionality in C#

In both the cases, we can use the constructor.

Constructor
Constructor is used to initialize an object (instance) of a class and it has the same name as the class name. Constructor is a like a method without any return type.
Destructor
Destructor in C# is a special method of a class, which will invoke automatically, when an instance of the class is destroyed.
Check the following example to find the number of instances created in a class, using C#.
Without using Inbuilt functionality in C#
Code
The following code will help to find the number of instances created in a class, using C#. In this example, we created 4 objects in a test class. Thus, before the execution of a constructor, we need to add static int count = 0. In each object initialization time of a class, the constructor will execute once. Thus, we will get the number of objects created by a class in C#.
  1. using System;
  2. namespace data
  3. {
  4. public class test
  5. {
  6. public static int count = 0;
  7. public test()
  8. {
  9. count = count + 1;
  10. }
  11. }
  12. public class Program
  13. {
  14. public static void Main()
  15. {
  16. test obj1 = new test();
  17. test obj2 = new test();
  18. test obj3 = new test();
  19. test obj4 = new test();
  20. Console.WriteLine(data.test.count);
  21. }
  22. }
  23. }
Output 4
Demo : Count the instance of a class in C#
Using Inbuilt functionality in C#
Interlocked
Interlocked helps in the threaded programs and it provides automatic operations for the variables that are shared by the multiple threads.
Code
  1. using System;
  2. using System.Threading;
  3. namespace data
  4. {
  5. public class test
  6. {
  7. public static int count = 0;
  8. public test()
  9. {
  10. Interlocked.Increment(ref count);
  11. }
  12. ~test()
  13. {
  14. Interlocked.Decrement(ref count);
  15. }
  16. }
  17. public class Program
  18. {
  19. public static void Main()
  20. {
  21. test obj1 = new test();
  22. test obj2 = new test();
  23. test obj3 = new test();
  24. Console.WriteLine(data.test.count);
  25. }
  26. }
  27. }
Output 3
Demo : Count instances of the class using Inbuilt functionality in C#
Reference

Summary

We learned how to find the number of instances created in a class, using C#. I hope this article is useful for all .NET beginners.