Nullable types

Nullable types

Nullable types are types wich allows null as a value. If you have for instance the following code:

    public class Student
    {
        // properties
        public int StudentID { get; set; }

        public string StudentName { get; set; }

        public DateTime DateOfBirth { get; set; }

        // ctor
        public Student(){}

    }

Now if you create a new student and without setting the birthdate of this student, the student has a birstdate with the default value of the DateTime object wicht is: 01-01-0001. Now if you persist this to the dabase and look at the student tabel there is a birtdate for all students. In some cases ( mostly ) this is not what you want. You want to execute a query finding all students without a birthdate like this

select * from Students
where Students.DateOfBirth is null

Therefor you need to declare the DateOfBirth as a nullable type, a nullable is type is default null and saved to the database as null.

    public class Student
    {
        // properties
        public int StudentID { get; set; }

        public string StudentName { get; set; }

        public DateTime? DateOfBirth { get; set; }

        // ctor
        public Student(){}

    }

Nullable types offers you two methods:

  • HasValue: bool indicating the type has a value
  • Value: the value self

The casting of the nullable types can be safely done if the value of the nullable type is checked:

    if(student.DateOfBirth .HasValue) //check for a value  
    {  
        if((DateTime) student.DateOfBirth ) //now this cast is safe  
        {  
           // Do something.  
        }  
    } 

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!