? operator

The conditional operator: ?

The use of the conditional operator is simple. It checkes an bool expression and if true it returns the first value and otherwise the second value

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

        public string StudentName { get; set; }

        public DateTime? DateOfBirth { get; set; }

        // ctor
        public Student(){}

        // methods
        public string ShortBirthDayString()
        {
            return DateOfBirth.HasValue ? DateOfBirth.Value.ToString("dd/mm/yyyy"): string.Empty;
        }

    }

Null condition operator

The null condition operator is introduced in C# 6. This operator checks if the value of an object is null and if null it returns null withoud any null reference exceptions. This will prevent a lot of null checking. And it this case we can rewrite the student class

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

        public string StudentName { get; set; }

        public DateTime? DateOfBirth { get; set; }

        // ctor
        public Student(){}

    }

            var student = new Student();
            var foundBirthDay = student.DateOfBirth?.ToString("dd/mm/yyyy");

Unless that the DateOfBirth of the student is null the foundBirthDay now isn't going to generate a null reference exception, the value just is null. This null condition operator will prevent that wil have to write a lot of null checking code. :-)

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

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