blog.jj5.net (2003 to 2005)

SqlBinary implicitly converts a null reference

Tue Mar 16 16:16:00 UTC+1100 2004

Categories:

Look at this code:

      SqlBinary o = null;
      Console.WriteLine(o); // prints: Null

The thing with this is that SqlBinary is a ValueType. You can't assign a null reference to a value type, but SqlBinary defines an implicit conversion for byte[] and allows construction of a SqlBinary that represents NULL by passing a null reference. So, the null reference is implicitly cast to a SqlBinary that has value equality with SqlBinary.Null before allocation to o.

Then look at this code:

      SqlBoolean b = null;

This code does not compile because SqlBoolean is a value type. But SqlBoolean is just as capable of representing NULL as SqlBinary is. The thing is that SqlBinary defines an implicit conversion for a reference type (byte[]), while SqlBoolean can not.

I know it's a hard problem, but I'm not sure that this is the best solution (although, maybe it is). Having lost a lot of faith in the people who designed this library, I wonder if this behavior is just an accident, or if it was considered and is 'by design'. If so, what is the justification for supporting an implicit conversion from a null reference to a SqlBinary.Null value..?

John.


Copyright © 2003-2005 John Elliot