Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

putting a tilde in front of a method call?

Tags:

c#

I was working through an example and I saw this...

#if DEBUG
    /// <summary>
    /// Useful for ensuring that ViewModel objects are properly garbage collected.
    /// </summary>
    ~ViewModelBase()
    {
        string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
        System.Diagnostics.Debug.WriteLine(msg);
    }
#endif

I tried to Google it but couldn't get any results... I was just wondering what it means. Anyone know?

Thanks

like image 637
Kenn Avatar asked Jan 20 '11 01:01

Kenn


3 Answers

It is the finalizer for the ViewModelBase class. It is called by the garbage collector before collection.

It is not really very useful because:

a) Garbage collection does really work and you do not need to test it.

b) It tells you nothing about your code when this gets called during normal execution, because for the most part the Garbage Collector just does its own thing and collects when it determines that there is memory pressure.

For the most part it is OK to not worry about the Garbage Collector - only worry about it when you have a real problem.

Also experience tells me - avoid using the finalizer since you are never sure what state the rest of your program will be in when it is called.

like image 108
Neil Avatar answered Nov 16 '22 17:11

Neil


It's a finalizer (a special method that is invoked by the garbage collector). Finalizers are designed to dispose unmanaged resources owned by an type implementing IDisposable even if its Dispose() method is never called.

The reason the author of this class wrote that debug code isn't 100% clear, but such debugging code is usually just a means of saying "hey dummy, you forgot to call Dispose() manually". It's a fairly common debugging aid (I've seen it in quite a lot of code), though I don't use it myself.

Sometimes an instance of a type holds precious resources and it's in your interest to call Dispose() as soon as you're finished with it. What the author's code is doing is saying "if I ever reach this Finalizer, you're failing to call Dispose() as soon as possible." It's not really what you'd use a Finalizer for in production code, though.

like image 31
Mark Simpson Avatar answered Nov 16 '22 18:11

Mark Simpson


This is called a finalizer.

It's called by the garbage collector at an indeterminate point in time when the object is collected, on the GC thread.

They also have a performance hit.

In general, you will never write a finalizer.
Finalizers are used by classes that directly own native resources (unless they use SafeHandles, which they should), and for special debugging tricks.

like image 38
SLaks Avatar answered Nov 16 '22 17:11

SLaks