Поделиться через


Nullable<T> Structure

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Represents an object whose underlying type is a value type that can also be assigned nulla null reference (Nothing in Visual Basic) like a reference type.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Structure Nullable(Of T As {Structure, New})
public struct Nullable<T>
where T : struct, new()

Type Parameters

  • T
    The underlying value type of the Nullable<T> generic type.

The Nullable<T> type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Nullable<T> Initializes a new instance of the Nullable<T> structure to the specified value.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 HasValue Gets a value indicating whether the current Nullable<T> object has a value.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Value Gets the value of the current Nullable<T> value.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals Indicates whether the current Nullable<T> object is equal to a specified object. (Overrides ValueType.Equals(Object).)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Retrieves the hash code of the object returned by the Value property. (Overrides ValueType.GetHashCode().)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetValueOrDefault() Retrieves the value of the current Nullable<T> object, or the object's default value.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetValueOrDefault(T) Retrieves the value of the current Nullable<T> object, or the specified default value.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns the text representation of the value of the current Nullable<T> object. (Overrides ValueType.ToString().)

Top

Operators

  Name Description
Public operatorStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Explicit(Nullable<T> to T) Returns the value of a specified Nullable<T> value.
Public operatorStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Implicit(T to Nullable<T>) Creates a new Nullable<T> object initialized to a specified value.

Top

Remarks

A type is said to be nullable if it can be assigned a value or can be assigned nulla null reference (Nothing in Visual Basic), which means the type has no value whatsoever. Consequently, a nullable type can express a value, or that no value exists. For example, a reference type such as String is nullable, whereas a value type such as Int32 is not. A value type cannot be nullable because it has enough capacity to express only the values appropriate for that type; it does not have the additional capacity required to express a value of null.

The Nullable<T> structure supports using only a value type as a nullable type because reference types are nullable by design.

The Nullable class provides complementary support for the Nullable<T> structure. The Nullable class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations.

Scenario

Use nullable types to represent things that exist or do not exist depending on the circumstance. For example, an optional attribute of an HTML tag might exist in one tag but not another, or a nullable column of a database table might exist in one row of the table but not another.

You can represent the attribute or column as a field in a class and you can define the field as a value type. The field can contain all the valid values for the attribute or column, but cannot accommodate an additional value that means the attribute or column does not exist. In this case, define the field to be a nullable type instead of a value type.

Fundamental Properties

The two fundamental members of the Nullable<T> structure are the HasValue and Value properties. If the HasValue property for a Nullable<T> object is true, the value of the object can be accessed with the Value property. If the HasValue property is false, the value of the object is undefined and an attempt to access the Value property throws an InvalidOperationException.

Boxing and Unboxing

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable<T> object, not the Nullable<T> object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable<T> structure initialized to the underlying value.

If the HasValue property of a nullable type is false, the result of a boxing operation is nulla null reference (Nothing in Visual Basic). Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is nulla null reference (Nothing in Visual Basic). When nulla null reference (Nothing in Visual Basic) is unboxed into a nullable type, the common language runtime creates a new Nullable<T> structure and initializes its HasValue property to false.

Examples

The following code example defines three rows of a table in the Microsoft Pubs sample database. The table contains two columns that are not nullable and two columns that are nullable.

' This code example demonstrates the Nullable(Of T) class.
' The code example defines a database table in which two columns 
' are nullable. In the application, an array of rows is created 
' and initialized. The table rows could subsequently be 
' written to a database.


Class Example
   ' Define the "titleAuthor" table of the Microsoft "pubs" database. 

   Public Structure titleAuthor
      ' Author ID; format ###-##-####
      Public au_id As String
      ' Title ID; format AA####
      Public title_id As String
      ' Author ORD is nullable.
      Public au_ord As Nullable(Of Short)
      ' Royalty Percent is nullable.
      Public royaltyper As Nullable(Of Integer)
   End Structure

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      ' Declare and initialize the titleAuthor array.
      Dim ta(2) As titleAuthor
      ta(0).au_id = "712-32-1176"
      ta(0).title_id = "PS3333"
      ta(0).au_ord = 1
      ta(0).royaltyper = 100

      ta(1).au_id = "213-46-8915"
      ta(1).title_id = "BU1032"
      ta(1).au_ord = Nothing
      ta(1).royaltyper = Nothing

      ta(2).au_id = "672-71-3249"
      ta(2).title_id = "TC7777"
      ta(2).au_ord = Nothing
      ta(2).royaltyper = 40

      ' Display the values of the titleAuthor array elements, and 
      ' display a legend.
      Display(outputBlock, "Title Authors Table", ta)
      outputBlock.Text &= "Legend:" & vbCrLf
      outputBlock.Text &= "An Author ORD of -1 means no value is defined." & vbCrLf
      outputBlock.Text &= "A Royalty % of 0 means no value is defined." & vbCrLf
   End Sub 'Main

   ' Display the values of the titleAuthor array elements.
   Public Shared Sub Display(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal dspTitle As String, _
                             ByVal dspAllTitleAuthors() As titleAuthor)
      outputBlock.Text += String.Format("*** {0} ***", dspTitle) & vbCrLf
      Dim dspTA As titleAuthor
      For Each dspTA In dspAllTitleAuthors
         outputBlock.Text += String.Format("Author ID ... {0}", dspTA.au_id) & vbCrLf
         outputBlock.Text += String.Format("Title ID .... {0}", dspTA.title_id) & vbCrLf
         outputBlock.Text += String.Format("Author ORD .. {0}", dspTA.au_ord.GetValueOrDefault(-1)) & vbCrLf
         outputBlock.Text += String.Format("Royalty % ... {0}", dspTA.royaltyper.GetValueOrDefault(0)) & vbCrLf
         outputBlock.Text &= vbCrLf
      Next dspTA
   End Sub 'Display
End Class 'Sample

'
'This code example produces the following results:
'
'*** Title Authors Table ***
'Author ID ... 712-32-1176
'Title ID .... PS3333
'Author ORD .. 1
'Royalty % ... 100
'
'Author ID ... 213-46-8915
'Title ID .... BU1032
'Author ORD .. -1
'Royalty % ... 0
'
'Author ID ... 672-71-3249
'Title ID .... TC7777
'Author ORD .. -1
'Royalty % ... 40
'
'Legend:
'An Author ORD of -1 means no value is defined.
'A Royalty % of 0 means no value is defined.
'
// This code example demonstrates the Nullable<T> class.
// The code example defines a database table in which two columns 
// are nullable. In the application, an array of rows is created 
// and initialized. The table rows could subsequently be 
// written to a database.

using System;

class Example
{
   // Define the "titleAuthor" table of the Microsoft "pubs" database. 
   public struct titleAuthor
   {
      // Author ID; format ###-##-####
      public string au_id;
      // Title ID; format AA####
      public string title_id;
      // Author ORD is nullable.
      public short? au_ord;
      // Royalty Percent is nullable.
      public int? royaltyper;
   }

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Declare and initialize the titleAuthor array.
      titleAuthor[] ta = new titleAuthor[3];
      ta[0].au_id = "712-32-1176";
      ta[0].title_id = "PS3333";
      ta[0].au_ord = 1;
      ta[0].royaltyper = 100;

      ta[1].au_id = "213-46-8915";
      ta[1].title_id = "BU1032";
      ta[1].au_ord = null;
      ta[1].royaltyper = null;

      ta[2].au_id = "672-71-3249";
      ta[2].title_id = "TC7777";
      ta[2].au_ord = null;
      ta[2].royaltyper = 40;

      // Display the values of the titleAuthor array elements, and 
      // display a legend.
      Display(outputBlock, "Title Authors Table", ta);
      outputBlock.Text += "Legend:" + "\n";
      outputBlock.Text += "An Author ORD of -1 means no value is defined." + "\n";
      outputBlock.Text += "A Royalty % of 0 means no value is defined." + "\n";
   }

   // Display the values of the titleAuthor array elements.
   public static void Display(System.Windows.Controls.TextBlock outputBlock, string dspTitle,
                              titleAuthor[] dspAllTitleAuthors)
   {
      outputBlock.Text += String.Format("*** {0} ***", dspTitle) + "\n";
      foreach (titleAuthor dspTA in dspAllTitleAuthors)
      {
         outputBlock.Text += String.Format("Author ID ... {0}", dspTA.au_id) + "\n";
         outputBlock.Text += String.Format("Title ID .... {0}", dspTA.title_id) + "\n";
         outputBlock.Text += String.Format("Author ORD .. {0}", dspTA.au_ord ?? -1) + "\n";
         outputBlock.Text += String.Format("Royalty % ... {0}", dspTA.royaltyper ?? 0) + "\n";
         outputBlock.Text += "\n";
      }
   }
}

/*
This code example produces the following results:

*** Title Authors Table ***
Author ID ... 712-32-1176
Title ID .... PS3333
Author ORD .. 1
Royalty % ... 100

Author ID ... 213-46-8915
Title ID .... BU1032
Author ORD .. -1
Royalty % ... 0

Author ID ... 672-71-3249
Title ID .... TC7777
Author ORD .. -1
Royalty % ... 40

Legend:
An Author ORD of -1 means no value is defined.
A Royalty % of 0 means no value is defined.

*/

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference