Why "Do not use object initializer for using variable"?

Hey there, I hope this is the correct sub-community to post this, but I just installed JetBrains ReSharper 2023.2 RC 1 - Build 232.0.20230726.93448-rc01 built on 2023-07-26 and got a new warning in my code: "Do not use object initializer for using variable"

In the changelog https://www.jetbrains.com.cn/en-us/help/qodana/new-in-2023-2.html its UsingStatementResourceInitialization

In code it wants me to change:

`using var jsonTextWriter = new JsonTextWriter(streamWriter) { Formatting = Formatting.None };`

Into:

````

        using var jsonTextWriter = new JsonTextWriter(streamWriter);
        jsonTextWriter.Formatting = Formatting.None;

````

I'm curious what the reasoning for this is. Is this just a style preference, or could there be any actual issues when you use an object initializer for using variable? Thanks

Edit: Also I don't know how formatting works on this forum for making code-blocks 🙃

0
2 comments

Hello Ron, thank you for your question.

The thing is that 'using' captures the variable only after the initialization block has been executed. A setter that is used inside init block may throw an exception and the object would be left undisposed, e.g. if you provide out-of-range value for it:
using var writer = new JsonTextWriter(sw)
{
  Formatting = (Formatting)(-1),
};
For now there is no way to know if the setter of library class may throw or not depending on input value, so ReSharper is suggesting the safer option. You can also take a look at Avoid object initializers & the using statement
Please let me know if you have any questions. Have a nice day!
1

Thanks, that makes sense

0

Please sign in to leave a comment.