Tuesday, February 19, 2008

"using" in C#

C# provides an interesting feature with "using". The target of "using" must implement the IDisposable interface which contains one member, Dispose(). After the block is executed, the Dispose() method is called on the target object.

using System;
namespace Doodle {
class DisposableExample : IDisposable {
public void Dispose() {
Console.Out.WriteLine("I'm being disposed!");
}
public static void Main() {
DisposableExample de = new DisposableExample();
using (de) {
Console.Out.WriteLine("Inside using.");
}
Console.Out.WriteLine("after using.");
Console.In.ReadLine();
}
}
}

This produces:

Inside using.
I'm being disposed!
after using.


This can be used to good effect with database connections. Instead of using the finally block to close connections, a "using" block can be more succinct.

using System;
using System.Data.SqlClient;

class Test {
private static readonly string connectionString = "Data Source=myMachine; Integrated Security=SSPI; database=Northwind";
private static readonly string commandString = "SELECT count(*) FROM Customers";

private static void Main() {
using (SqlConnection sqlConnection = new SqlConnection(connectionString)) {
using (SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection)) {
sqlConnection.Open();
int count = (int)sqlCommand.ExecuteScalar();
Console.Out.WriteLine("count of customers is " + count);
}
}
Console.In.ReadLine();
}
}


"using" can also be helpful with files as this example shows:

using System;
using System.IO;

class Test {
///
/// Example of "using" with files.
/// This repeated creates files and closes them subtly by the "using" statement.
///

private static void Main() {
for (int i = 0; i < 5000; i++) {
using (TextWriter w = File.CreateText("C:\\tmp\\test\\log" + i + ".txt")) {
string msg = DateTime.Now + ", " + i;
w.WriteLine(msg);
Console.Out.WriteLine(msg);
}
}
Console.In.ReadLine();
}
}

No comments: