NotNull

It seems the promised support for Nullable types is not what people expected it to be. What everyone expected was, for example, that we could map database values directly onto .NET variables. In other words, when we have a varchar in SQL-Server that has the value [null], we could just copy it into a string value in .NET.


In your (C#) code, you specifiy a variable as a nullable type by adding a questionmark when declaring the variable. An example is shown below.


But there are some issues.



  • According to Paul Wilson, they’re not actually implemented into the framework. There is support for them, but they don’t really map. When you take a look at the example code below, you can see the declaration of a nullable integer. In the other two lines you see that you still need to check wether the value of the datareader is null or not. You cannot just insert the value of the datareader into the variable as this will throw an exception when it is indeed null.
  • Also converting types and binding it to datagrids for example, will not just work.
  • Paul also claims that the implementation is done purely by the C# team, and there’s no VB.NET support. Frans Bouma had the same issue, but some readers responded with links to the VBTeam weblog and to Panopticon Central where they also discuss the VB.NET & C# issue. So it it is possible in VB.NET, but with the same restictions I just mentioned.
  • But there’s more to it. David Kean ran some performance tests, an noticed some (minor?) performance issues when using nullable types.

So some support has been implemented, but there are issues that need to be considered before just using these everywhere. And with the 70% code reduction claim for ASP.NET, Microsoft probably didn’t use too many nullable types. 😉

.csharpcode
{
font-size: 10pt;
color: black;
font-family: Courier New , Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0px; }
.rem { color: #008000; }
.kwrd { color: #0000ff; }
.str { color: #006080; }
.op { color: #0000c0; }
.preproc { color: #cc6633; }
.asp { background-color: #ffff00; }
.html { color: #800000; }
.attr { color: #ff0000; }
.alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0px;
}
.lnum { color: #606060; }

Example

   1:  int? nullInt;
   2:  if (dataReader.IsDBNull(index)) { nullInt = null; }
   3:  else { nullInt = dataReader.GetInt32(index); }

You may also like...

1 Response

  1. Patrick Wellink says:

    Minor? performance issues

    Are they nullable then ?

Click on a tab to select how you'd like to leave your comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.