How to Assign Null Value to Value Type Using Nullable Types

Introduction

As a developer it is sometimes necessary to provide a null value to a value type variable, which is not possible normally, because when you want to pass a null value, the compiler will throw an error. To overcome this the .Net Framework provides a new feature called Nullable datatypes to assign a null value for value type variables.

A Nullable datatype can store null values in adition to the normal set of values. For example, if you define a Nullable Int datatype then it can store either a null value or an integer value.

Implementation of Nullable types

The following code example shows an implementation of Nullable type. It defines a student class that consists of member fields to store a student name, class name, DOB and age. Ensure that if the student does not know their date of birth then the Date of Birth field will be null.

Code

    class Student

    {

        private string Name;

        private string Class;

        private Nullable<DateTime> DOB;

        private int Age;

        public Student()

        {

        }

        public void setStudent(string StudentName, string ClassName, DateTime dob)

        {

            this.Name = StudentName;

            this.Class = ClassName;

            this.Class = dob;

            TimeSpan sp = DateTime.Now.Date - dob;

            this.Age = sp.Days / 365;

        }

        public void setStudent(string StudentName, string ClassName, int age)

        {

            this.Name = StudentName;

            this.Class = ClassName;

            this.DOB = null;

            this.Age = age;

        }

        public void Display()

        {

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

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

            if (this.DOB.HasValue)

                Console.WriteLine("Date of Birth{0:MM:yy}", this.Class); // HasValue property helps to determine whether the dob contains value or not

            Console.WriteLine("Age {0}", this.Age);

        }

        static void Main(string[] args)

        {

            Student st = new Student();

            st.setStudent("Amit", "3rd", "20/02/2001");

            st.Display();

 

            Student st1 = new Student();

            st1.setStudent("Amar", "1rd", 5);

            st1.Display();

            Console.ReadLine();

        }

    }

 


Recommended Free Ebook
Similar Articles