Archive for November, 2006

SQL 2005 SP2 – New features

SQL Server 2005 Service Pack 2 CTP (November 2006) is now available for download, not just fixing bugs but also adding plenty of new features.

.NET 3.0 released

The .NET Framework 3.0 (formerly WinFX) has now been released, bringing these new technologies to the .NET platform:

Free E-Learning

Microsoft is currently offering free introductory E-Learning clinics for WCF, WPF and WF.

Downloads

.NET Framework 3.0 will be included with Windows Vista, and the redistributable package for Windows XP and Server 2003 is downloadable now from Microsoft.

Also available are Visual Studio 2005 extensions for WF development, and a preview of the extensions for WCF & WPF which will be included in Visual Studio Orcas.

List.ForEach

The generic List class, introduced in .NET 2.0, has a ForEach method that lets you perform a specified action on each element of a list. The action can be declared using a delegate as either a named or anonymous method. Here’s an example that prints the squares of numbers between 1 and 100 using an anonymous method:

// create a list of numbers, 1 to 100
List<int> nums = new List<int>();
for (int i = 1; i <= 100; i++) nums.Add(i);
 
// display the square of each number
nums.ForEach(
    delegate(int n) { Console.WriteLine(Math.Pow(n,2)); }
);

This excellent article, Performance of foreach vs. List.ForEach from Did it with .NET, compares List.ForEach with foreach and for loops and discusses the performance implications.

Avoiding assignment vs. equality bugs

Here’s a quick tip to help prevent bugs caused by confusion between the C# equality operator (“==”) and the assignment operator (“=”). Although the compiler will issue a warning, it’s still possible to compile code like this:

bool flag = true;
if (flag = false) { /* do something */ }

The intention is to test whether the value of flag is false, but instead the value false is assigned to the variable flag. I’m sure every programmer’s done it, especially if you come from a BASIC background where the assignment and equality operators are both “=”.

It seems counterintuitive, but try putting the literal constant operand on the left:

if (true == flag) { /* do something */ }

Now, if you accidently use “=” instead of “==” then it doesn’t matter because the code won’t compile and you’ll easily spot the mistake; the left hand side of an assigment must always be a variable.

SqlConnection – Close() or Dispose()

There seems to be a lot of confusion about how to clean up after using a SqlConnection object. Should you call Close(), Dispose(), Close() then Dispose(), or neither?

Here are some relevant facts we need to consider:

  1. When an open SqlConnection goes out of scope, its underlying physical database connection will not be closed or returned to the connection pool by the garbage collector;
  2. Dispose() always calls Close() implicitly;
  3. Dispose() clears the ConnectionString, Close() does not;
  4. In future versions of ADO.NET, the SqlConnection.Dispose method might free other unmanaged resources, in addition to the database connection.

What conclusions can we draw?

  1. We must at least call Close() or Dispose(), otherwise the database connection won’t be released;
  2. There’s no need to call both Close() and Dispose();
  3. If we’re going to open the connection again, we should Close() not Dispose();
  4. When we’re completely finished with the SqlConnection, we should call Dispose() to make sure that all unmanaged resources are released, both now and in the future.

The tempation of symmetry after calling Open() is to always call Close(), as was the case in classic ADO, but I’ve shown that in the case of SqlConnection we only need to call Dispose(). Better still, make sure Dispose() is always called implicitly by enclosing your SqlConnection objects in a using statement.

Two interesting things about C# strings

1. Iterating with foreach

The String class implements the IEnumerable interface, so you can iterate over it using a foreach statement. Each iteration will yield subsequent characters from the string:

string myString =
    "I'm out of the loop, and that's the way I like it";
 
foreach (char ch in myString)
{
    Console.WriteLine(ch);
}

2. The indexer

The String class provides an indexer, it returns a Char object that corresponds to the specified position of the string, for example:

string myString =
    "But it is, perhaps, the end of the beginning";
 
char first = myString[0]; // 'B'
char last  = myString[myString.Length - 1]; // 'g'

Dispose(), Try-Catch and Using

The using statement, not to be confused with the more accustomed using directive, is a useful shorthand for working with classes that need to explicitly release unmanaged resources.

Bad

Consider opening a connection to a SQL Server database using a SqlConnection. Here’s a typical (bad) example:

string cnnStr = "Data Source=(local);Initial Catalog=Northwind2;Integrated Security=SSPI;";
SqlConnection cnn = new SqlConnection(cnnStr);
cnn.Open();
// ...work with database
cnn.Dispose();

If the database isn’t available then the call to Open will throw a SqlException. This means that Dispose will never be called, so the underlying database connection will not be closed or returned to the connection pool.

Better

A more resilient solution would be to wrap this code in a try-finally block, to make sure that the Dispose method is always called:

string cnnStr = "Data Source=(local);Initial Catalog=Northwind2;Integrated Security=SSPI;";
SqlConnection cnn = new SqlConnection(cnnStr);
try
{
    cnn.Open();
    // ...work with database
}
finally
{
    cnn.Dispose();
}

Best

A more succinct, but functionally equivalent, solution is to use the using statement:

string cnnStr = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI;";
using (SqlConnection cnn = new SqlConnection(cnnStr))
{
    cnn.Open();
    // ... work with database
}

The object provided to the using statement must implement the IDisposable interface, which guarantees that the object imlpements a Dispose method. The object is always disposed as soon as control leaves the using block scope, even if it’s because an exception was thrown. This way, as with the try-finally example above, you can always guarantee that the underlying database connection will be released.

Not just for databases

Any class that uses unmanaged resources, such as file handles, network sockets or registry handles, can be placed in a using statement. Here are a few example from the .NET class library: