Count instances of the class using Inbuilt functionality in C#

CSharp · Console

/Program.cs

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);
		}
	}
}
;