.NET decompilers reorder methods, causing trouble with COM Interop

Resharper almost keeps class methods in order, but it puts everything with a [DispId] attribute in front. Teleric JustDecompile seems to sort things in alphabetical order. Neither seems to have an option to turn this disservice off and just output class members in the order they are found in the IL.

The order of methods in .NET does usually not matter except when dealing with P/Invoke or COM Interop. In those cases the order of the methods must correspond to the order of the pointers in the vtable, and getting it wrong will create highly mysterious errors at runtime, usually of the “access violation” kind. I spent about an hour starting at the screen and trying to figure out why do I end up calling a wrong method.

My use case was to generate a run-time callable wrapper (RCW) from a type library and then decompile it and fix it a little (more about it in later posts).

Bottom line: if while doing you main work you program beautifies the input in some way (be it inserting new lines or sorting method names alphabetically), consider either not doing it, or if you insist, then always, always, always provide a way to opt out. Sooner or later your beautification is bound to break something important.

Leave a Reply

Your email address will not be published. Required fields are marked *