8

I'm poking around a few dlls within the XNA framework using ILSpy and came across this:

class KerningHelper
{
    private void !KerningHelper()
    {
        ((IDisposable)this).Dispose();
    }
}

What is the exclamation mark for in the above? Is it an issue with ILSpy, or something else?

Note, the class has a separate destructor: private unsafe void ~KerningHelper().

George Duckett
  • 31,770
  • 9
  • 95
  • 162
  • 2
    In CLI/C++ the !KerningHelper would symbolise a `finalizer` rather than a `destructor` perhaps it's something to do with that? Have a look here: http://en.wikipedia.org/wiki/C%2B%2B/CLI#Finalizers_and_automatic_variables – Nick Apr 17 '12 at 08:46
  • 1
    It isn't valid C# either way, so I'm guessing some IL representation that is then translated back slightly wrong. – Adam Houldsworth Apr 17 '12 at 08:47
  • @AdamHouldsworth: I did check writing my own class with that and came to the same conclusion. I'm interested in what it was originally / what it's for / what the original syntax is. :) – George Duckett Apr 17 '12 at 08:49

1 Answers1

7

As the comments stated, the exclamation mark is the C++/CLI marker for a finalizer method. Unlike traditional C++ destructors (~) that are called when you explicitly dispose of an object, finalizers are called by the garbage collector thread. You can see the official details here.

I would expect ILSpy to translate the !KerningHelper() to ~KerningHelper(), since C++/CLI finalizer is equivalent to C#'s destructor - it's a non-deterministic method that occurs when the GC gets to it, unlike C++/CLI's explicit ~destructor, which is called when you call delete or an explicit Dispose call is made.

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
  • Thanks for the explanation, what confused me is that the `KerningHelper` had a destructor too, so I guess ILSpy uses `!` as it's different to a destructor. If you know of a use for a finalizer I'd appreciate it as in the class I've found I think `dispose` should get called anyway so I don't understand its use (i.e. when would a finalizer be used instead of/as well as a destructor?). – George Duckett Apr 17 '12 at 09:06