Nullable types are one of those great little exceptions to help you with the impedance mismatch between object-oriented applications and relational databases. Let's take a fakeOrder classThat maps toOrders tableIn your database. The class might look like this:
Order class
Using System; Using System. collections; Public Class Order { Private Int _ Id; Private String _ Number = String . Empty; Private Decimal _ Amount; Private Datetime _ shipdate; Public Int Id { Get { Return _ Id ;;}} Public String Number { Get { Return _ Number ;} Set {_ Number = Value ;}} Public Decimal Amount { Get { Return _ Amount ;} Set {_ Amount = Value ;}} Public Datetime shipdate { Get { Return _ Shipdate ;} Set {_ Shipdate = Value ;}} Public Order (){}}
Now if an order has not shipped,ShipdateFor the order will beNullInOrders tableAnd you wowould perform CT the shipdate to be null (nothing in VB) in the order object as well. However, datetime isStruct(Value type) and cannot be null. If not assigned, shipdate will defaultSystem. datetime. minvalue. This is the mismatch.
We can get around this inC #2.0By making _ shipdate A nullable datetime type. You can make it a nullable type by declaring it either:
- Nullable <datetime> _ shipdate;
- Datetime? _ Shipdate;
With the nullable structure being defined as follows:
Nullable types
StructNullable<T>{Public BoolHasvalue;PublicT value ;}
Now the new class is defined as follows:
Order class with nullable shipdate
Using System; Using System. collections; Public Class Order { Private Int _ Id; Private String _ Number = String . Empty; Private Decimal _ Amount; Private Datetime ? _ Shipdate; Public Int Id { Get { Return _ Id ;;}} Public String Number { Get { Return _ Number ;} Set {_ Number = Value ;}} Public Decimal Amount { Get { Return _ Amount ;} Set {_ Amount = Value ;}} Public Datetime ? Shipdate { Get { Return _ Shipdate ;} Set {_ Shipdate = Value ;}} Public Order (){}}
Checking for null
If_ ShipdateIs not assigned now, it will have a null value and you can determine if it has been assigned by the following statements:
If (order. shipdate! = NULL )...
Or
If (order. shipdate. hasvalue )...
Invalidoperationexception
If _ shipdate has not been assigned and you try to extract the datetime value from it, you will get an invalidoperationexception:
Datetime shipdate = order. shipdate. value; // throws exception if not assigned
C # nullable types will play a big role in defining business objects and data transfer objects and how they map to relational databases.