Registry Mirror
Skip to content

Conversation

@MSchmoecker

@MSchmoecker MSchmoecker commented Jul 5, 2025 •

Copy link
Copy Markdown
Contributor

Problem

ILSpy could match an instance method call with a static method reference. This can happen when resolving a method whose current definition is static but the IL actually calls an instance method. I.e. the method was originally an instance method but was changed to static.
This results in the decompiled code to silently drop the instance argument on the evaluation stack. While this produces valid/compilible C# code, it does not accurately decompile the given code.

Example:

the reference code was changed from

class A {
    static A instance;
    void Ref() {}
}

to

class A {
    static A instance;
    static void Ref() {}
}

the original code is

A.instance.Ref();

but gets wrongly decompiled to

A.Ref(); // should still be A.instance.Ref();

Solution

  • The given code searches for a matching reference method. Since static and non-static are not matching, we are excluding those as potential matches. In our case this means we don't match the Ref method, so ILSpy decompiles the code without a reference and produces A.instance.Ref()
  • I am not sure how to write a test because the compile and decompile step require different reference assemblies

@siegfriedpammer

siegfriedpammer commented Jul 5, 2025 •

Copy link
Copy Markdown
Member

You can write a correctness test based on IL files.

Yes, it needs two separate assemblies.

@dgrunwald

Copy link
Copy Markdown
Member

I think you could maybe test this with a .il based test that calls a method in the .NET stdlib, e.g. a hand-written call instruction to Console.WriteLine that expects WriteLine to be an instance method.

This would have to be a pretty-test, as it would not be possible to recompile the decompiled code.

@siegfriedpammer
siegfriedpammer merged commit eafccdb into icsharpcode:master Jul 5, 2025
@siegfriedpammer

Copy link
Copy Markdown
Member

Thank you very much for your contribution!

@MSchmoecker

Copy link
Copy Markdown
Contributor Author

Thanks so much for providing the test case and merging!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants