ILSpy
ILSpy copied to clipboard
struct in using do not box
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.
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?
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.
I would keep the cast but add a comment that the cast is due to the constrained prefix...