|
|
6 Aug 2007
|
Nullable Type
Nullable value is sometime desirable. Here is an example: You declare an EndDate variable dt and the value of this EndDate variable is not known yet. It is logically not correct to assign a date to dt variable. Under this circumstance, nullable type comes in handy.
In VS2005, C# is more mature than VB.Net in handling nullable type. The following is a comparison table:
| C# > |
VB.Net equivalent |
| Nullable dt; |
Dim dt as Nullable(Of DateTime) |
| DateTime? dt; |
this is a C# shorten form. VB.Net has no equivalent |
| dt = null; |
dt=Nothing |
| if (dt.HasValue) { ... } |
If dt.HasValue Then .... End If |
| if (dt !=null) { ... } |
VB.Net has no equivalent syntax |
Reading null value from database, C# syntax is cleaner:
dt= dbreader.GetValue(dbreader.GetOridinal("DateTimeField")) as DateTime?;
But in VB.Net, you need to:
If IsDBNull(dbreader.GetValue(dbreader.GetOrdinal("DateTimeField"))) Then
dt = Nothing
Else
dt = Ctype(dbreader.GetValue(dbreader.GetOrdinal("DateTimeField")), Nullable(Of DateTime))
End If
When nullable type has no value, it is null in C#(or Nothing in VB). Writing this to database will cause an exception. You must use System.DBNull.Value instead if you want to write null to database.
|