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#.
- using System;
-
- namespace data
- {
- public class test
- {
- public static int count = 0;
- public test()
- {
- count = count + 1;
- }
- }
-
- public class Program
- {
- public static void Main()
- {
- test obj1 = new test();
- test obj2 = new test();
- test obj3 = new test();
- test obj4 = new test();
- Console.WriteLine(data.test.count);
- }
- }
- }
Output 4
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
- using System;
- using System.Threading;
-
- namespace data
- {
- public class test
- {
- public static int count = 0;
- public test()
- {
- Interlocked.Increment(ref count);
- }
-
- ~test()
- {
- Interlocked.Decrement(ref count);
- }
- }
-
- public class Program
- {
- public static void Main()
- {
- test obj1 = new test();
- test obj2 = new test();
- test obj3 = new test();
- Console.WriteLine(data.test.count);
- }
- }
- }
Output 3
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.