Implementation of Nullable types

The following code example shows an implementation of Nullable types in Visual Basic and C#. The code example defines an Employee class that consists of member fields to store information on employee name, marital status, and date of anniversary. The class defines the field for date of anniversary as Nullable and ensures that the field stores a null value if the employee is unmarried. While retrieving values from these fields, the class uses the HasValue property, which is available in Nullable types. This property helps determine whether the Nullable field has a value assigned to it or contains a null value.

Visual Basic

Public Shared Sub Main()

Dim e1 As New Employee("Stephen", True)

e1.Anniversary = DateTime.Today.AddMonths(-



Dim e2 As New Employee("Thomas", False)

e2.Anniversary = DateTime.Today.AddMonths(-



Console. ReadLine()

End Sub

End Class

class Employee {

private string _name; private bool _married;

private Nullable<DateTime> _mAnniversary;

public Employee(string name, bool married) {

this._name = name; this._married = married; if (!this._married)

this._mAnniversary = null;

public Nullable<DateTime> Anniversary {

return this._mAnniversary;

if (this._married)

this._mAnniversary = value;

else this._mAnniversary = null;

public void ShowDetails() {


Console.WriteLine("Name : {0}", this._name);

Console.WriteLine("Married : {0}", this._married ? "Yes" : "No"); if (this._mAnniversary.HasValue)

Console.WriteLine("Anniversary : {0:MMMM d}", this._mAnniversary);

el se

Console.WriteLine("Anniversary : none");

static void Main(string[] args) {

Employee e1 = new Employee("Stephen", true); e1.Anniversary = DateTime.Today.AddMonths(-5); e1.ShowDetails();

Employee e2 = new Employee("Thomas", false); e2.Anniversary = DateTime.Today.AddMonths(-10); e2.ShowDetails(); Console.ReadLine();

Was this article helpful?

0 0

Post a comment