379

Is it possible to make this code a little more compact by somehow declaring the 2 variable inside the same using block?

using (var sr = new StringReader(content))
{
    using (var xtr = new XmlTextReader(sr))
    {
        obj = XmlSerializer.Deserialize(xtr) as TModel;
    }
}
3
  • 7
    Don't use new XmlTextReader(). Use XmlReader.Create() Commented Feb 22, 2012 at 13:48
  • 12
    new XmlTextReader() has been deprecated since .NET 2.0. By using XmlReader.Create(), you will get the best derived XmlReader class possible, as opposed to just the one XmlTextReader class. Commented Feb 22, 2012 at 13:53
  • 3
    Come on, it's not like this question was about XmlTextReader specifically! Please stay on topic! Commented Sep 15, 2021 at 14:53

2 Answers 2

707

The accepted way is just to chain the statements:

using (var sr = new StringReader(content))
using (var xtr = new XmlTextReader(sr))
{
    obj = XmlSerializer.Deserialize(xtr) as TModel;
}

Note that the IDE will also support this indentation, i.e. it intentionally won’t try to indent the second using statement.

Sign up to request clarification or add additional context in comments.

10 Comments

@MD.Unicorn Yes, exactly. This is intentional – this is the most concise way C# offers: removing the parentheses and omitting the indentation. Notice how the IDE offers explicit support for this (otherwise it would indent the second statement).
@KonradRudolph My question is kind of confusing, but I'm asking if this is actually a discrete language feature designed for multiple usings, or just the same as if (x) if (y) { z; }. I think your comment answers that, though; I'm reading it as the latter?
@peachykeen Yes, it’s definitely not a discrete language feature, merely nested blocks. The IDE does treat it specially for the purpose of indentation though.
I really wish C# had a form of using that didn't begin a new block, but instead disposed the variables at the end of the block in which they're declared, something like: { using var x = new Reader(); x.Read(); }
IL code still remains the same. In all two nested try finally blocks get generated in the IL code. The xtr variable which gets instantiated later gets disposed in the inner finally block and the sr variable which got instantiated before gets disposed in the outer finally block.
|
160

The following only works for instances of the same type! Thanks for the comments.

This sample code is from MSDN:

using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

4 Comments

This only work when variables are of the same type.
that only seems to work if both objects are of the same type
Then declare the variables as IDisposable and cast later?
@Robert Jørgensgaard Engdahl: Yes, that works too. Just tried it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.