Count instances of the class
Solution 1
You can holds global static counter in your program.
This is a simple thread safe solution:
class MyClass
{
static int counter = 0;
public MyClass()
{
Interlocked.Increment(ref counter);
}
~MyClass()
{
Interlocked.Decrement(ref counter);
}
}
also take a look at the following similar question - Count number of objects of class type within class method
Solution 2
this :
public class MyClass
{
private static int instances = 0;
public MyClass()
{
instances++;
}
~MyClass()
{
instances--;
}
public static int GetActiveInstances()
{
return instances;
}
}
use :
MyClass c1 = new MyClass();
MyClass c2 = new MyClass();
int count = MyClass.GetActiveInstances();
Solution 3
Only if you implement a counting mechanism inside the constructor (increment) and finalizer (decrement). But even that will not account for instances which are really inactive (noone has any reference to them) but have not been collected yet.
Moreover, adding a finalizer to a class -- no matter how trivial -- will adversely affect performance, which is an argument against doing so.
Solution 4
Try this one:
public class MyClass
{
public static int activeCount = 0;
public MyClass() => activeCount++;
~MyClass() => activeCount--;
}
//In the main
var testClass1 = new MyClass();
var testClass2 = new MyClass();
Console.WriteLine(MyClass.activeCount);
Solution 5
public class MyClass
{
public static int countinstance =0;
MyClass(){ countinstance ++;}
~ MyClass() {countinstance --; }
}
simple and easy get instance active by countinstance
Tomas
Updated on November 19, 2020Comments
-
Tomas over 3 years
Possible Duplicate:
how can i find out how many objects are created of a class in C#Is it possible to get number of instances which is active(created and not yet destroyed) for selected class?
For example:
public class MyClass { } ... var c1 = new MyClass(); var c2 = new MyClass(); count = GetActiveInstances(typeof(MyClass))
Should return 2. If GC destroy any of these classes then 1 or 0.
-
Daniel Hilgarth over 11 yearsThis is a C# question, not Java.
-
Andras Zoltan over 11 yearssee also stackoverflow.com/questions/934619/…
-
Yannick Blondeau over 11 years+1 for the use of
lock
-
Waihon Yew over 11 years@YannickBlondeau:
lock
should always target aprivate
field though. If you are going to do it, then do it right. -
Jon Hanna over 11 yearsNo. Never put a lock in a finaliser. You don't want the finaliser thread blocking for any reason. Use
Interlocked.Increment
andInterlocked.Decrement
if you must do something like this from a finaliser. -
Yannick Blondeau over 11 yearsThanks @Jon, I didn't know that...
-
Zack about 9 yearsI get
The modifier 'public' is not valid for this item
on the finalizer line when trying to compile, because finalizers cannot have access modifiers.