I'm wondering if the use of object initializers inside using statements somehow prevents the correct disposal of the resource declared inside them, e.g.
using (Disposable resource = new Disposable() { Property = property })
{
// ...
}
I've read that object initializers are nothing but synctatic sugar, which the compiler translates to something similar to the following code:
MyClass tmp = new MyClass();
tmp.Property1 = 1;
tmp.Property2 = 2;
actualObjectYouWantToInitialize = tmp;
Even if I may appear as a confused ignorant, I'd like to ask for clarifications. Does the fact that the initialized object is (as far as I understand) a pointer to another object (which is also a pointer, as far as I know), interfere with the disposal of the resource done by a using
statement?
public class Test : IDisposable { public string Property { get => "Hello"; set => throw new Exception();} public void Dispose() { Console.WriteLine("Disposed"); } }
. Dispose wasn't called when runningusing(var x = new Test() { Property = "Test"})
. – Raidtry-finally
, which the compiler translates theusing
to, checks if the resource isnull
before callingDispose()
on it, which it is when initialization fails. – Culminationresource
variable being set and then properties set on it (which is wrong). That mental model is probably why some people think the object will be disposed. – Federica