Odd class member syntax shown in ILSpy
Asked Answered
D

1

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().

Durward answered 17/4, 2012 at 8:43 Comment(3)
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: en.wikipedia.org/wiki/C%2B%2B/…Cockrell
It isn't valid C# either way, so I'm guessing some IL representation that is then translated back slightly wrong.Nelsonnema
@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. :)Durward
P
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.

Pipes answered 17/4, 2012 at 9:0 Comment(1)
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?).Durward

© 2022 - 2024 — McMap. All rights reserved.