0

ShellFile implements IDisposable.

public string LocalizedName => new ShellFile(Executable).FileDescription;

I was unable to find anything on the internet about using disposable objects in expression-bodied members.
Is the ShellFile instance correctly disposed, or should I do something like this ?

public string LocalizedName
{
    get
    {
        using ShellFile shellFile = new(Executable);
        return shellFile.FileDescription;
    }
}
Scover
  • 93
  • 9
  • 5
    "*Is the ShellFile instance correctly disposed*" -- No. "*or should I do something like this*" -- Yes. – canton7 Jun 09 '22 at 13:59
  • You can't have multiple lines in an expression body. I suppose you could make an extension for that `T WithDispose where TObj : IDisposable (this TObj d, Func func) { using (d) return func(d); }` then you can do `public string LocalizedName => new ShellFile(Executable).WithDispose(f => f.FileDescription);` but why would you bother? – Charlieface Jun 09 '22 at 14:05
  • i wouldn't, i only wanted to know if .net automatically handled disposing in those cases. – Scover Jun 09 '22 at 14:07
  • For that it would need to track the lifetime of each variable and call dispose on it as soon as it exits the scope, in which case the garbage collection would never occur because each object would be cleaned up as soon as. This is what C++ does. – GSerg Jun 09 '22 at 14:25

0 Answers0