Search code examples
c#using-statement

using statement with multiple variables


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

Solution

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