using statement with multiple variables [duplicate]

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.

When should I use the using Statement? [duplicate]

If a class implements IDisposable then it will create some unmanaged resources which need to be ‘disposed’ of when you are finished using them. So you would do something like: SqlConnection awesomeConn = new SqlConnection(connection); // Do some stuff awesomeConn.Dispose(); To avoid forgetting to dispose of the resourses (in this case close the database connection), … Read more

The C# using statement, SQL, and SqlConnection

It’s possible to do so in C# (I also see that code is exactly shown in MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx). However, if you need to be defensive and for example log potential exceptions which would help troubleshooting in a production environment, you can take this approach: private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection … Read more

Does Java have a using statement?

Java 7 introduced Automatic Resource Block Management which brings this feature to the Java platform. Prior versions of Java didn’t have anything resembling using. As an example, you can use any variable implementing java.lang.AutoCloseable in the following way: try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable()) { … } Java’s java.io.Closeable interface, implemented by streams, automagically extends AutoCloseable, … Read more