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:
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.