Thank you Mattias,
I had never considered that multiple using statements before the code block
were valid. I certainly haven't seen it used like this before. Your second
technique is also interesting except that it requires the overhead of the
cast.
My typical pattern is:
SqlConnection cn = null;
SqlCommand cmd = null;
try
{
cn = new SqlConnection(...);
cmd = cn.CreateCommand();
// Do something
}
finally
{
if(cmd != null) cmd.Dispose();
if(cn != null) cn.Close();
}
This keeps everything strongly typed from the start. Still your first
technique is intriguing in that it also eliminates the chance of forgetting
the cleanup code in the finally block...
--
Peter
> Mattias Sj�gren spake:
>
> Peter,
>
> >I will often use the try ... finally pattern in C# if there is
> more than one
> >type of resource to clean up. The using statement only supports
> one type at
> >a time.
>
> Yes, but you can easily nest them
>
> using ( DisposableType1 d1 = new DisposableType1() )
> using ( DisposableType2 d2 = new DisposableType2() )
> using ( DisposableType3 d3 = new DisposableType3() ) {
> // ...
> }
>
> or
>
> using ( IDisposable d1 = new DisposableType1(), d2 = new
> DisposableType2() ) {
> DisposableType1 dt1 = d1 as DisposableType1;
> DisposableType2 dt2 = d2 as DisposableType2;
> // ...
> }
>
>
> Mattias
You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.