More In-Depth About Nulls And DBNull
page 3 of 7
by Brian Mains
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 33727/ 87

Nullable Types

Nullable types are a new feature to .NET 2.0, where they can make any value type support null values.  By defining a value type with a question mark after it (in C#), or using the Nullable<T> class (in VB.NET), the value type can support nulls simply by assigning null to it.  Nullable types add two additional members to it: the Value property and the HasValue property.  HasValue determines whether the nullable value actually has a value, because if the Value property (which represents the actual value) is accessed before being assigned a value, an exception is raised.

However, a nullable type is still an instance of the value type (int? or Nullable(Of Int32)) is still a value of type int), and isn't meant to represent or handle DBNull objects.  Although when using the table adapter feature of .NET 2.0 nullable types are used, they cannot handle DBNull, because of what is described in the next section.

View Entire Article

User Comments

Title: Nasty syntax for getting round this   
Name: Tyrannosaurs
Date: 2008-02-20 11:50:11 AM
You cast a null date time to a dbnull like this:

datetime? myDateTime;

myDateTime = null;

.... parameters.add(...).value = (object)myDateTime ?? System.DBNull.Value;

It's pretty horrible but works and is no worse than most of the alternatives.
Title: DBNULL   
Name: g
Date: 2007-11-19 6:37:19 AM
this concept can be dealt in more detail
Title: Datetime & DBNull Reply   
Name: Brian
Date: 2007-11-10 11:29:55 PM
You can't cast directly; DBNULL and DateTIme are two separate object types, and you can't cast one to the other. However, in an ADO.NET datarow object, the underlying value is object, which could accept both. However, if the field is not null, then you can't assign a null value to it. It all depends on your code.
Title: Datetime&DBnull   
Name: Erick
Date: 2007-11-09 6:49:21 AM
When I assigned DBNull.Value to System.Datetime, it raised a exception. Can I set a Datetime field of the database to null by using DBNull.Value in

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-05-18 3:20:35 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search