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

You have a variable that is a numeric type, which will hold a numeric value obtained from a database. The database may return this value as a null. You need a simple clean way to store this numeric value, even if it is returned as a 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <table border="1">
             <tr>
                 <td>
                     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                 </td>
                 <td>
                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></td>
             </tr>
         </table>
     </div>
 </form>
</body>
</html>
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;
      else
          Label1.Text = "Does not have a value (NULL)";

  }
}

No comments:

Post a Comment