Advertisements

Count instances of the class using C#


Introduction

In this article, 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 article, 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 nothing, but it 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 instance created in a class, using C#.

1.Without using Inbuilt functionality in C#

Code

The following code will help to find the number of instance 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

Demo : Count the instance of a class in C#

2.Using Inbuilt functionality in C#

Interlocked

Interlocked helps in the threaded programs and it provides atomic 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

Demo : Count instances of the class using Inbuilt functionality in C#

Reference

Summary

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: