Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using statement with multiple variables [duplicate]

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;     } } 
like image 424
Antony Scott Avatar asked Feb 22 '12 13:02

Antony Scott


2 Answers

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.

like image 113
Konrad Rudolph Avatar answered Oct 03 '22 16:10

Konrad Rudolph


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. } 
like image 23
Frank Bollack Avatar answered Oct 03 '22 14:10

Frank Bollack