Book Image

C# Programming Cookbook

By : Dirk Strauss
Book Image

C# Programming Cookbook

By: Dirk Strauss

Overview of this book

During your application development workflow, there is always a moment when you need to get out of a tight spot. Through a recipe-based approach, this book will help you overcome common programming problems and get your applications ready to face the modern world. We start with C# 6, giving you hands-on experience with the new language features. Next, we work through the tasks that you perform on a daily basis such as working with strings, generics, and lots more. Gradually, we move on to more advanced topics such as the concept of object-oriented programming, asynchronous programming, reactive extensions, and code contracts. You will learn responsive high performance programming in C# and how to create applications with Azure. Next, we will review the choices available when choosing a source control solution. At the end of the book, we will show you how to create secure and robust code, and will help you ramp up your skills when using the new version of C# 6 and Visual Studio
Table of Contents (21 chapters)
C# Programming Cookbook
Credits
About the Author
Acknowledgements
About the Reviewer
www.PacktPub.com
Preface
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:

  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 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.