Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
C# Programming Cookbook

You're reading from   C# Programming Cookbook Quick fixes to your common C# programming problems, with a focus on C# 6.0

Arrow left icon
Product type Paperback
Published in Jul 2016
Publisher Packt
ISBN-13 9781786467300
Length 476 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Dirk Strauss Dirk Strauss
Author Profile Icon Dirk Strauss
Dirk Strauss
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. New Features in C# 6.0 FREE CHAPTER 2. Classes and Generics 3. Object-Oriented Programming in C# 4. Composing Event-Based Programs Using Reactive Extensions 5. Create Microservices on Azure Service Fabric 6. Making Apps Responsive with Asynchronous Programming 7. High Performance Programming Using Parallel and Multithreading in C# 8. Code Contracts 9. Regular Expressions 10. Choosing and Using a Source Control Strategy 11. Creating a Mobile Application in Visual Studio 12. Writing Secure Code and Debugging in Visual Studio 13. Creating a Web Application in Azure Index

Null-conditional operator

The worst thing that a developer can do is not check for null in code. This means that there is no reference to an object, in other words, there is a null. Reference-type variables have a default value of null. Value types, on the other hand, cannot be null. In C# 2, developers were introduced to the nullable type. To effectively make sure that objects are not null, developers usually write sometimes elaborate if statements to check whether objects are null or not. C# 6.0 made this process very easy with the introduction of the null-conditional operator.

It is expressed by writing ?. and is called the question-dot operator. The question is written after the instance, right before calling the property via the dot. An easy way to think of the null-conditional operator is to remember that if the left-hand side of the operator is null, the whole expression is null. If the left-hand side is not null, the property is invoked and becomes the result of the operation. To really see the power of the null-conditional operator is to see it in action.

Getting ready

We will create another class that will illustrate the use of the null-conditional operator. The method will call a Student class to return a count of students in the resulting list. We will check to see whether the Student class is valid before returning the student count.

How to do it…

  1. Create another class called Recipe2NullConditionalOperator beneath the last class you wrote in the Creating your Visual Studio project recipe:
    public static class Recipe2NullConditionalOperator
    {
    
    }
  2. Add a method called GetStudents to the class and add the following code to it:
    public static int GetStudents()
    {
        List<Student> students = new List<Student>(); 
        Student st = new Student();
    
        st.FirstName = "Dirk";
        st.LastName = "Strauss";
        st.JobTitle = "";
        st.Age = 19;
        st.StudentNumber = "20323742";
        students.Add(st);
    
        st.FirstName = "Bob";
        st.LastName = "Healey";
        st.JobTitle = "Lab Assistant";
        st.Age = 21;
        st.StudentNumber = "21457896";
        students.Add(st);
    
        return students?.Count() ?? 0;            
    }
  3. Next, add a third class to your code called Student with the following properties:
    public class Student
    {
        public string StudentNumber { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string JobTitle { get; set; }
    }
  4. Our Student class will be the object we will call from our GetStudents method. In the Program.cs file, add the following code:
    int StudentCount = Chapter1.Recipe2NullConditionalOperator.GetStudents();
                if (StudentCount >= 1)
                    Console.WriteLine($"There {(StudentCount > 1 ? "are " : "is ")}{StudentCount} student{(StudentCount > 1 ? "s" : "")} in the list.");
                else
                    Console.WriteLine($"There were {StudentCount} students contained in the list.");
                Console.Read();
  5. Running the console application will result in the application telling us that there are two students contained in the list. This is expected, because we added two Student objects to our List<Student> class:
    How to do it…
  6. To see the null-conditional operator in action, modify the code in your GetStudents method to set the students variable to null. Your code should look like this:
    public static int GetStudents()
    {
        List<Student> students = new List<Student>(); 
        Student st = new Student();
    
        st.FirstName = "Dirk";
        st.LastName = "Strauss";
        st.JobTitle = "";
        st.Age = 19;
        st.StudentNumber = "20323742";
        students.Add(st);
    
        st.FirstName = "Bob";
        st.LastName = "Healey";
        st.JobTitle = "Lab Assistant";
        st.Age = 21;
        st.StudentNumber = "21457896";
        students.Add(st);
    
        students = null;
        return students?.Count() ?? 0;            
    }
  7. Run the console application again, and see how the output has changed:
    How to do it…

How it works…

Consider the code we used in the return statement:

return students?.Count() ?? 0;

We told the compiler to check whether the List<Student> class' variable students is null. We did this by adding ? after the students object. If the students object is not null, we use the dot operator, and the Count() property becomes the result of the statement.

If the students object however is null, then we return zero. This way of checking for null makes all that if(students != null) code unnecessary. The null check sort of fades into the background and makes it much easier to express and read null checks (not to mention less code).

If we had to change the return statement to a regular Count() method without the null-conditional operator, we would see an ArgumentNullException was unhandled error:

return students.Count();

Calling Count() on the students object without using the null-conditional operator breaks the code. The null-conditional operator is an exciting addition to the C# language because it makes writing code to check for null a lot easier. Less code is better code.

You have been reading a chapter from
C# Programming Cookbook
Published in: Jul 2016
Publisher: Packt
ISBN-13: 9781786467300
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime