ReSharper 2024.1 Help

Code inspection: Do not use object initializer for 'using' variable

Initializing a using variable with an object initializer might be a problem if an exception is thrown during the initialization. This is possible because the compiler creates and initializes the object before the execution enters the using clause. If an exception is thrown during the initialization, the program will never enter the using clause and the object will not be disposed.

ReSharper reports such cases and suggests converting the initialization to a simple assignment and moving the initialization of the properties inside the using block:

class MyDisposable : IDisposable { public int Prop { get => throw new(); set => throw new(); } public void Dispose() { // TODO release managed resources here } } class Test { public Test() { using (var x = new MyDisposable { Prop = 1 }) { Console.WriteLine(x); } } }
class MyDisposable : IDisposable { public int Prop { get => throw new(); set => throw new(); } public void Dispose() { // TODO release managed resources here } } class Test { public Test() { using (var x = new MyDisposable()) { x.Prop = 1; Console.WriteLine(x); } } }

In the above example, ReSharper can access the sources of the object class MyDisposable and check whether any of its properties actually throw an exception. If they do not, the problem will not be reported. However, if you initialize any library class this way, ReSharper will assume that an exception is possible and issue the warning.

Last modified: 08 April 2024