How To Create a Value Type That Can Be Initialized to Null

You have a numeric type variable, which will hold a numeric value obtained from a database. The database may return this value as null. You need a simple, clean way to store this numeric value, even if it is returned as null.

Use a nullable value type. There are two ways of creating a nullable value type. The first way is to use the ? type modifier:

In addition, testing the nullable type can be done in
One of two ways. First, by using the HasValue property as shown here:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NullableType.aspx.cs" Inherits="NullableType" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
 <title>Untitled Page</title>
 <form id="form1" runat="server">
         <table border="1">
                     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></td>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class NullableType : System.Web.UI.Page
  protected void Page_Load(object sender, EventArgs e)

  protected void Button1_Click(object sender, EventArgs e)
      //Essentially both of the following statements are equivalent:
      int? myDBInt = null;
      Nullable<int> myDBInt = new Nullable<int>();

      if (myDBInt.HasValue)
          Label1.Text = "Has a value: " + myDBInt.Value;
          Label1.Text = "Does not have a value (NULL)";

Next Post Previous Post
No Comment
Add Comment
comment url