using statement with multiple variables

Antony Scott picture Antony Scott · Feb 22, 2012 · Viewed 108.6k times · Source

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;
    }
}

Answer

Konrad Rudolph picture Konrad Rudolph · Feb 22, 2012

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.