Tuesday, March 18, 2008

C# statement using and null.

Frequently calling of method Dispose (or finish of statement using) for a object means, that the object is not actual (because a resources are deleted in Dispose). If we check actuality of the object by checking for null, then we cannot use the checking after using.

For example, this code will not set null to the object customerDisposableClass

Trace.WriteLine("after definition ==> customerClass == null: " + (customerDisposableClass == null));
using (customerDisposableClass = new CustomerDisposableClass())
{
// statements
}
Trace.WriteLine("after Dispose() ==> customerClass == null: " + (customerDisposableClass == null));
Console output: 
consoleOutput1
Sure, we can set null by statement customerDisposableClass = null and add section try .. finally
(because if a exception will be raised inside statement using we will not set null).
I tried to find a suitable solution and can suggest to implement a next wrapper
public class CustomerClassWrapper: IDisposable
{
CustomerClass customerClass;
public CustomerClassWrapper(
CustomerClass customerClass,
CustomerDisposableClass customerDisposableClass)
{
this.customerClass = customerClass;
this.customerClass.customerDisposableClass = customerDisposableClass;
}
#region IDisposable
public void Dispose()
{
customerClass.customerDisposableClass.Dispose();
customerClass.customerDisposableClass = null;
}
#endregion
}

and use the wrapper by next way:
Trace.WriteLine("after definition ==> customerClass == null: " + (customerDisposableClass == null));
using (new CustomerClassWrapper(this, new CustomerDisposableClass()))
{
// statements
}
Trace.WriteLine("after Dispose() ==> customerClass == null: " + (customerDisposableClass == null));
Console output:
consoleOutput2 
Yes, I understand the solution helps per class (not for all all classes).
If somebody can suggest better solution, please, post in comments.
Reference

C# Language Specification. The using statement.

Statement "using" in blog csharp-tips

sources (from Code project "C# tips samples")

No comments: