views:

69

answers:

3

How do I keep a count of the number of times that objects of a specific class (type?) are getting disposed in the lifetime of my application. Imagine I have a class A, now, I want to count how many times the objects of A get collected by the GC.

I hope I am phrasing this right because I was asked this in an interview today and the answer I gave did not satisfy the interviewer. And this is what I imagine he was trying to ask.

What I said was that one could keep a static field called count in the class A and increment it in the Finalize() call of that object.

The answer he was expecting was something called a static block. I've never heard of this in .NET/C#. Can someone explain what's this static block?

+1  A: 

Use a tool like memprofiler, Redgate Ants, dotTrace, CLR Profiler (needs admin rights for .NET 3.5 apparently) or the team edition of Visual Studio.

Mitch Wheat
I'll be sure to check these out. Thanks Mitch.
tsps
A: 

Maybe he was referring to a static constructor for the class?

public class Foo {

   public static Foo() { /* gets called once before first operator new */ }

}
plinth
@plinth, this is what I thought. But even at that, how can this help you keep track of how many times the class is disposed?
James
It doesn't. That's the confusing part.
plinth
Yeah I think its a case of `that's the answer that's in the book`. Not quite sure what book they were reading...
James
A: 

A static block is really another name for a Static Constructor in C#. It is called automatically to intialize a class before the first instance is created. I can't see how this will help you keep track of how many times a class is disposed though. Only way I could think of would be to have your class implement IDisposable, have a static field called disposeCount and increment it on every call to Dispose or to be sure as you rightly said in the Finalize method. Your answer was defintely not wrong, and you should point that out to them if you get a 2nd interview :)

James
Unfortunately, that was the final interview. I just told him I was not aware of something like that in .NET. I'll be more confident with my .NET skills next time. :)
tsps