ReSharper 2024.1 Help

Code inspection: Do not use object initializer for 'using' variable (object initializer expression may throw exception while initializing '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.

If any of the object properties are initialized with an expression involving a method call, ReSharper reports a problem of possible exceptions inside that call and suggests introducing a new variable and replacing the call with that variable. This ensures that any potential exceptions will happen during the initialization of that new variable and that the using variable will be disposed in any cas.

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

In the above example, ReSharper can access the sources of the initialization method CalculateValue() and check whether it actually throws an exception. If it does not, the problem will not be reported. However, if you use any library method this way, ReSharper will assume that an exception is possible and issue the warning.

Last modified: 08 April 2024