Code inspection: Do not use object initializer for 'using' variable (object initializer expression may throw exception while initializing 'using' variable)

Last modified: 08 April 2024

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, JetBrains Rider 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.

In the above example, JetBrains Rider 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, JetBrains Rider will assume that an exception is possible and issue the warning.