ILSpy icon indicating copy to clipboard operation
ILSpy copied to clipboard

struct in using do not box

Open OwnageIsMagic opened this issue 2 years ago • 3 comments

Input code

using System;

using (new Str()) ;

struct Str : IDisposable
{
    public void Dispose() {}
}

Erroneous output

Str str = default(Str);
        try
        {
        }
        finally
        {
// this is wrong
            ((IDisposable)str).Dispose(); 
// structs do not box in using pattern
// see corresponding blog post from Eric Lippert
// https://stackoverflow.com/a/2413844/5647513
        }

Details

Sharplab uses v7 https://sharplab.io/#v2:CYLg1APgAgTAjAWAFDKgBgAQAoB2BTAdwwGUAXAJywEoqMBuVTXQjAJTwDMzKb7Ht8RAMIAbAM7VaDFEjEUArgGNSJChhAYAkgBEAlmIAOAezEBDAEYi8yAN7IMDjFADMTgCwY9hk3moYbAL7IQTLknBhy5Eoq7FwUtvaOLu6e+sZivrSBwcioMBiiYupaXukWVglIjk6uUB6lPn7ZSAFAA=

Also tested in ILSpy version 8.1.1.7464.

OwnageIsMagic avatar Sep 25 '23 03:09 OwnageIsMagic

Unfortunately there's no good way to represent a constrained.call in C#. Imagine the Str.Dispose method was an explicit interface implementation -- the using statement would still be able to call it without boxing, but how would you do the same without a using statement?

dgrunwald avatar Sep 29 '23 07:09 dgrunwald

I think since user intentionally opt-ins (using is C# 1 feature -- always on by default) output should prefer correct semantics vs compile-ability. At least it's possible to drop cast for non explicit implementations and add a comment on explicit.

OwnageIsMagic avatar Sep 29 '23 18:09 OwnageIsMagic

I would keep the cast but add a comment that the cast is due to the constrained prefix...

siegfriedpammer avatar Sep 29 '23 18:09 siegfriedpammer