A Null Object

Introduction

We already know that, to create an object, you can declare a variable of its class. Here is an example:

public class Exercise
{
    static void Main()
    {
        Microwave machine;
    }
}

public class MicrowaveOven
{
    
}

Once you have a class, you can pass it to a function and use it, such as displaying its values to a user. Here is an example:

using System;

public class Exercise
{
    void Present(Microwave mw)
    {
        Console.Write("Make: ");
        Console.Write(mw.Make);
    }

    static void Main()
    {
        Microwave machine;
    }
}

Practical LearningPractical Learning: Introducing the Nullity

  1. Start Microsoft Visual Studio. In the Visual Studio 2019 dialog box, click Create a New Project and click Next (if Microsoft Visual Studio was already running, on the main menu, click File -> New -> Project...)
  2. In the list of projects templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the project Name to AppliancesStore1
  5. Click Create
  6. In the Solution Explorer, right-click AppliancesStore1 -> Add -> Class...
  7. In the middle list, make sure Class is selected.
    Change the file Name to MicrowaveOven
  8. Click Add
  9. Right-click inside the Code Editor -> Remove and Sort Usings
  10. Create the class as follows:
    namespace AppliancesStore1
    {
        class MicrowaveOven
        {
            public string Make        { get; set; }
            public string Model       { get; set; }
            public double Capacity    { get; set; }
            public int    MenuOptions { get; set; }
            public double Price       { get; set; }
        }
    }
    
  11. In the Solution Explorer, right-click Form1.cs and click View Designer
  12. Design the form as follows:

    Introducing the Nullity

    Control (Name) Text
    GroupBox gbxDeviceSummary Device Summary
    Label   Make:
    TextBox txtMake
    Label   Model:
    TextBox txtModel
    Label   Capacity:
    TextBox txtCapacity
    Label   Cubic-Foot
    Label   Menu Options:
    TextBox txtMenuOptions
    Label   Price:
    TextBox txtPrice
  13. Right-click the form and click View Code
  14. Right-click anywhere in the document and click Remove and Sort Usings
  15. Change the constructor as follows:
    uusing System.Windows.Forms;
    
    namespace AppliancesStore1
    {
        public partial class Form1 : Form
        {
    
            public Form1()
            {
                InitializeComponent();
    
                MicrowaveOven device = Create();
    
                Present(device);
    
                // A nested function
                MicrowaveOven Create()
                {
                    MicrowaveOven machine = new MicrowaveOven()
                    {
                        Make = "Farberware",
                        Model = "FMO12AHTBSG",
                        Capacity = 1.2,
                        MenuOptions = 9,
                        Price = 108.65
                    };
                    
                    return machine;
                }
    
                // Another nested function
                void Present(MicrowaveOven mo)
                {
                    txtMake.Text = mo.Make;
                    txtModel.Text = mo.Model;
                    txtCapacity.Text = mo.Capacity.ToString();
                    txtMenuOptions.Text = mo.MenuOptions.ToString();
                    txtPrice.Text = mo.Price.ToString("F");
                }
            }
        }
    }
  16. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Introducing the Nullity

  17. Close the browser and return to your programming environment
  18. Change the design of the form as follows:

    Introducing the Nullity

    Control (Name) Text
    GroupBox gbxDeviceSetup Device Setup
    Label   Make:
    TextBox txtManufacturrer
    Label   Model:
    TextBox txtIdentification
    Label   Capacity:
    TextBox txtVolume
    Label   Cubic-Foot
    Label   Menu Options:
    TextBox txtNumberOfMenus
    Label   Price:
    TextBox txtValue
    Button btnCreate Create
    GroupBox gbxDeviceSummary Device Summary
    Label   Make:
    TextBox txtMake
    Label   Model:
    TextBox txtModel
    Label   Capacity:
    TextBox txtCapacity
    Label   Cubic-Foot
    Label   Menu Options:
    TextBox txtMenuOptions
    Label   Price:
    TextBox txtPrice
  19. Double-click the Create button

Getting a Null Object

You are not allowed to use an object that doesn't have values, such as an object that has not previously been initialized. If you do, you would receive an error.

If you declare a variable for a class but don't initialize it, the compiler reserves memory for the object but doesn't put any meaningful value in that memory area: the area is filled with garbage. That's why it is a good idea to (always) initialize the object. Still, sometimes when declaring the variable, you may not have the values necessary for the object. In this case, you can indicate that the object is null.

To support null objects, the C# language provides a keyword named null. To apply the nullity to an object, assign the null keyword to its declaration. Here is an example:

public class Exercise
{
    static void Main()
    {
        Microwave machine = null;
    }
}

When necessary, you can ask the compiler to reset an object to nullity. To do this, assign null to the object. Here is an example:

using System;

public class Exercise
{
    void Present(Microwave mw)
    {
        Console.WriteLine("Microwave Oven");
        Console.WriteLine("---------------------------------------");
        Console.Write("Make and Model: ");
        Console.Write(mw.Make);
        Console.Write(" ");
        Console.WriteLine(mw.Model);
        Console.Write("Capacity:       ");
        Console.Write(mw.Capacity);
        Console.WriteLine(" cubic-foot");
        Console.Write("Menu Options:   ");
        Console.WriteLine(mw.MenuOptions);
        Console.Write("Price:          ");
        Console.WriteLine(mw.Price);
        Console.WriteLine("=======================================");
    }

    static void Main()
    {
        Exercise exo = new Exercise();

        Microwave machine = new Microwave()
        {
            Make = "Farberware",
            Model = "FMO12AHTBSG",
            Capacity = 1.2,
            MenuOptions = 9,
            Price = 108.65
        };

        exo.Present(machine);

        machine = null;
    }
}

public class Microwave
{
    public string Make { get; set; }
    public string Model { get; set; }
    public double Capacity { get; set; }
    public int MenuOptions { get; set; }
    public double Price { get; set; }
}

Returning a Null Object

Sometimes, while your application is running, one way or another, for any reason, an object can lose its values. For example, a function that is supposed to produce an object may fail to return a complete or appropriate object. Consider the following example:

public class Exercise
{
    Microwave Create()
    {
        return null;
    }

    static void Main()
    {
        Exercise exo = new Exercise();

        Microwave machine = exo.Create();

        exo.Present(machine);
    }
}

public class Microwave
{   
}

This code would result in an error because you are attempting to use a null object.

Practical LearningPractical Learning: Accessing a Null Object

  1. Change the document as follows:
    using System.Windows.Forms;
    
    namespace AppliancesStore1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            MicrowaveOven CreateStoreItem()
            {
                MicrowaveOven machine;
    
                if(txtManufacturer.Text == "")
                    machine = null;
                else
                {
                    machine = new MicrowaveOven()
                    {
                        Make = txtManufacturer.Text,
                        Model = txtIdentification.Text,
                        Capacity = double.Parse(txtVolume.Text),
                        MenuOptions = int.Parse(txtNumberOfMenus.Text),
                        Price = double.Parse(txtValue.Text)
                    };
                }
    
                return machine;
            }
    
            void Present(MicrowaveOven mo)
            {
                txtMake.Text = mo.Make;
                txtModel.Text = mo.Model;
                txtCapacity.Text = mo.Capacity.ToString();
                txtMenuOptions.Text = mo.MenuOptions.ToString();
                txtPrice.Text = mo.Price.ToString("F");
            }
    
            private void btnCreate_Click(object sender, System.EventArgs e)
            {
                MicrowaveOven device = CreateStoreItem();
    
                Present(device);
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    Introducing the Nullity

  3. Click the Create button:

    Introducing the Nullity

  4. On the Application Store message box, click Quit

Comparing an Object to Nullity

Before using an object, you must make sure that it holds appropriate values, or at least that it is not null. Before using an object, to check whether it is null, using the equality operator, ==, to compare it to null. Obviously, the reason you are checking the nullity of an object is so you can take an appropriate action one way or another. Here is an example:

The Nullity of a Value

using System;

public class Exercise
{
    void Present(MicrowaveOven mo)
    {
        if(mo == null)
        {
            Console.WriteLine("The object is null.");
            Console.WriteLine("=======================================");
        }
        else
        {
            Console.WriteLine("Microwave Oven");
            Console.WriteLine("---------------------------------------");
            Console.Write("Make and Model: ");
            Console.Write(mo.Make);
            Console.Write(" ");
            Console.WriteLine(mo.Model);
            Console.Write("Capacity:       ");
            Console.Write(mo.Capacity);
            Console.WriteLine(" cubic-foot");
            Console.Write("Menu Options:   ");
            Console.WriteLine(mo.MenuOptions);
            Console.Write("Price:          ");
            Console.WriteLine(mo.Price);
            Console.WriteLine("=======================================");
        }
    }

    static void Main()
    {
        MicrowaveOven machine = null;
        Exercise exo = new Exercise();

        exo.Present(machine);

        machine = new MicrowaveOven()
        {
            Make = "Farberware",
            Model = "FMO12AHTBSG",
            Capacity = 1.2,
            MenuOptions = 9,
            Price = 108.65
        };

        exo.Present(machine);

        machine = null;
        exo.Present(machine);
    }
}

public class MicrowaveOven
{
    public string Make { get; set; }
    public string Model { get; set; }
    public double Capacity { get; set; }
    public int MenuOptions { get; set; }
    public double Price { get; set; }
}

This would produce:

The object is null.
=======================================
Microwave Oven
---------------------------------------
Make and Model: Farberware FMO12AHTBSG
Capacity:       1.2 cubic-foot
Menu Options:   9
Price:          108.65
=======================================
The object is null.
=======================================
Press any key to continue . . .

Practical LearningPractical Learning: Comparing an Object to Nullity

  1. Change the code as follows:
    using System.Windows.Forms;
    
    namespace AppliancesStore1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void Present(MicrowaveOven mo)
            {
                if (mo == null)
                    MessageBox.Show("Ain't no microwave oven like that in the store.",
                                    "Appliances Store");
                else
                {
                    txtMake.Text = mo.Make;
                    txtModel.Text = mo.Model;
                    txtCapacity.Text = mo.Capacity.ToString();
                    txtMenuOptions.Text = mo.MenuOptions.ToString();
                    txtPrice.Text = mo.Price.ToString("F");
                }            
            }
    
            private void btnCreate_Click(object sender, System.EventArgs e)
            {
                MicrowaveOven device = CreateStoreItem();
    
                Present(device);
                
                // Nested function
                MicrowaveOven CreateStoreItem()
                {
                    MicrowaveOven machine;
                    
                    if(txtManufacturer.Text == "")
                        machine = null;
                    else
                    {
                        machine = new MicrowaveOven()
                        {
                            Make = txtManufacturer.Text,
                            Model = txtIdentification.Text,
                            Capacity = double.Parse(txtVolume.Text),
                            MenuOptions = int.Parse(txtNumberOfMenus.Text),
                            Price = double.Parse(txtValue.Text)
                        };
                    }
                
                    return machine;
                }
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. Click the Create button:

    Introducing the Nullity

  4. On the Application Store message box, click OK
  5. In the top text boxes, enter the following values:
    Make:         Black+Decker
    Model: 		EM720CB7
    Capacity:     0.7
    Menu Options: 10
    Price:        75.95

    Introducing the Nullity

  6. Click the Create button:

    Introducing the Nullity

  7. Close the form and return to Microsoft Visual Studio

Comparing an Object for Non-Nullity

On the other hand, to find out whether an object is not null, you can use the != operator with the null keyword as the right operand. Here is an example:

using System;

public class Exercise
{
    void Present(MicrowaveOven mo)
    {
        if(mo != null)
        {
            Console.WriteLine("Microwave Oven");
            Console.WriteLine("---------------------------------------");
            Console.Write("Make and Model: ");
            Console.Write(mo.Make);
            Console.Write(" ");
            Console.WriteLine(mo.Model);
            Console.Write("Capacity:       ");
            Console.Write(mo.Capacity);
            Console.WriteLine(" cubic-foot");
            Console.Write("Menu Options:   ");
            Console.WriteLine(mo.MenuOptions);
            Console.Write("Price:          ");
            Console.WriteLine(mo.Price);
            Console.WriteLine("=======================================");
        }
    }

    static void Main()
    {
        MicrowaveOven machine = null;
        Exercise exo = new Exercise();

        exo.Present(machine);

        machine = new MicrowaveOven()
        {
            Make = "Black+Decker",
            Model = "EM720CB7",
            Capacity = 0.7,
            MenuOptions = 10,
            Price = 75.95
        };

        exo.Present(machine);

        machine = null;
        exo.Present(machine);
    }
}

public class MicrowaveOven
{
    public string Make { get; set; }
    public string Model { get; set; }
    public double Capacity { get; set; }
    public int MenuOptions { get; set; }
    public double Price { get; set; }
}

This would produce:

Microwave Oven
---------------------------------------
Make and Model: Black+Decker EM720CB7
Capacity:       0.7 cubic-foot
Menu Options:   10
Price:          75.95
=======================================
Press any key to continue . . .

The Nullity of a Value

Nullity Operators

Checking the Compatibility of an Object

The equality operator is used to find out whether an object is equal to a certain value. Because an application may deal with various types of values, an alternative is to find out whether a certain object is compatible with another. To assist you with this operation, the C# language provide a Boolean operator named is. There are various scenarios you can use this operator. The formula to find out whether an object is null is:

instance-object is null

You can use an if conditional statement to obtain this information. Here is an example:

using System;

public class Exercise
{
    static void Present(MicrowaveOven mo)
    {
        if(mo is null)
        {
            Console.WriteLine("There is no machine to show.");
            Console.WriteLine("=======================================");
        }
        else
        {
            Console.WriteLine("Microwave Oven");
            Console.WriteLine("---------------------------------------");
            Console.Write("Make and Model: ");
            Console.Write(mo.Make);
            Console.Write(" ");
            Console.WriteLine(mo.Model);
            Console.Write("Capacity:       ");
            Console.Write(mo.Capacity);
            Console.WriteLine(" cubic-foot");
            Console.Write("Menu Options:   ");
            Console.WriteLine(mo.MenuOptions);
            Console.Write("Price:          ");
            Console.WriteLine(mo.Price);
            Console.WriteLine("=======================================");
        }
    }

    static void Main()
    {
        MicrowaveOven machine = null;

        Present(machine);

        machine = new MicrowaveOven()
        {
            Make        = "Aicok",
            Model       = "EM131A5C-BS",
            Capacity    = 1.1,
            MenuOptions = 11,
            Price       = 79.95
        };

        Present(machine);

        machine = null;
        Present(machine);
    }
}

public class MicrowaveOven
{
    public string Make     { get; set; }
    public string Model    { get; set; }
    public double Capacity { get; set; }
    public int MenuOptions { get; set; }
    public double Price    { get; set; }
}

This would produce:

There is no machine to show.
=======================================
Microwave Oven
---------------------------------------
Make and Model: Aicok EM131A5C-BS
Capacity:       1.1 cubic-foot
Menu Options:   11
Price:          79.95
=======================================
There is no machine to show.
=======================================
Press any key to continue . . .

The Nullity of a Value

Checking the Type of an Object

We have already been introduction to a data type named object. This is the most fundamental type in C# (and the .NET Framework) and, in some cases, it can be used in place of any data type. As a matter of fact, if you are creating a function that would treat various types of objects, you can pass an object type to it. Then, in the body of the function, before doing anything, find out what type was passed as argument. To do that, use the is operator to compare the argument to the desired type. Here is an example:

using System;

public class Exercise
{
    static void Present(object obj)
    {
        if (obj is Microwave)
        {
            Microwave mw = (Microwave)obj;

            Console.Write("Make and Model: ");
            Console.Write(mw.Make);
            Console.Write(" ");
            Console.WriteLine(mw.Model);
            Console.Write("Capacity:       ");
            Console.WriteLine(mw.Capacity);
            Console.Write("mw Options:   ");
            Console.WriteLine(mw.MenuOptions);
            Console.WriteLine("==================================");
        }
    }

    static void Main()
    {
        Microwave machine = null;

        Present(machine);

        machine = new Microwave()
        {
            Make = "Farberware",
            Model = "FMO12AHTBSG",
            Capacity = 1.2,
            MenuOptions = 9
        };

        Person friend = new Person();
        Present(friend);

        Present(machine);

        Bicycle voyage = new Bicycle();
        Present(voyage);
    }
}

public class Microwave
{
    public string Make { get; set; }
    public string Model { get; set; }
    public double Capacity { get; set; }
    public int MenuOptions { get; set; }
}

public class Person
{
    public string Name { get; set; }
}

public class Bicycle
{
    public int Speeds { get; set; }
    public double Price { get; set; }
}

The Nullity of a Variable

Introduction

When you declare a variable, you ask the compiler to reserve a certain area and amount of memory to eventually hold a value for that variable. Here is an example:

class Exercise
{
	static void Main()
    {
    	int quantity;
    }
}

When you have declared a variable like that, no clear value is stored in the reserved area of the computer memory. A value is referred to as null when it cannot be clearly determined. A null value is not 0 because 0 is a an actual value. When declaring a variable, if you don't have a clear value for it, you can ask the compiler to treat its value as null.

A Null String

To support null values, the C# language provides a keyword named null. To apply it, initialize the variable with it. The main rule is that you must assign the value before the variable can be used.

When declaring a string variable, if you don't have a value for it, set it as null. Here are examples:

class Employment
{
    static void Main()
    {
        string status = null;
        string firstName = null, lastName = null;
        double hourlySalary = 22.27, timeWorked = 42.50;

        status = "Full Time";
        firstName = "Martial";
        lastName = "Engolo";

        System.Console.WriteLine("Employee Details");
        System.Console.WriteLine("============================");
        System.Console.Write("Employee Name: ");
        System.Console.Write(firstName);
        System.Console.Write(" ");
        System.Console.WriteLine(lastName);
        System.Console.Write("Status: ");
        System.Console.WriteLine(status);
        System.Console.Write("Hourly Rate: ");
        System.Console.WriteLine(hourlySalary);
        System.Console.Write("Time Worked: ");
        System.Console.WriteLine(timeWorked);
    }
}

A Nullable Primitive Type

In C#, normally, not all variables can hold null values. When declaring a variable, to indicate that it can hold either an actual value or it can be null, after its data type, add a question mark. You have two options.

You can assign null when declaring the variable. This would be done as follows:

class Exercise
{
    static void Main()
    {
	    data-type? variable-name = null;
	
        // You can use the variable
    }
}

Once again, if you plan to to display the value of the variable, you must first specify a value for it. Here are examples:

class Employment
{
    static void Main()
    {
        string status = null;
        string firstName = null, lastName = null;

        double?  hourlySalary = null;
        double ? timeWorked = null;
        int     ?category = null;

        status = "Full Time";
        firstName = "Martial";
        lastName = "Engolo";
        category = 3;
        timeWorked = 42.50;
        hourlySalary = 22.27;

        System.Console.WriteLine("Employee Details");
        System.Console.WriteLine("============================");
        System.Console.Write("Employee Name: ");
        System.Console.Write(firstName);
        System.Console.Write(" ");
        System.Console.WriteLine(lastName);
        System.Console.Write("Status: ");
        System.Console.WriteLine(status);
        System.Console.Write("Hourly Rate: ");
        System.Console.WriteLine(hourlySalary);
        System.Console.Write("Time Worked: ");
        System.Console.WriteLine(timeWorked);
        System.Console.Write("Pay Category: ");
        System.Console.WriteLine(category);
    }
}

As another option, you can assign null after the variable has been declared. This would be done as follows:

class Exercise
{
    static void Main()
    {
	    data-type? variable-name;
	
    	variable-name = null;
	
	    // You can use the variable
    }
}

The Null-Conditional Operator

Consider a class used to describe some houses:

public class House
{
    public int Bedrooms;

    public House()
    {
        Bedrooms = 1;
    }
}

We already saw how to find out whether an object of such a class is currently valid. Here is an example:

int beds = -1;
House habitat = null;
Description desc = new Description();

if (habitat == null)
{
    beds = 0;
}
else
{
    beds = habitat.Bedrooms;
}

In this case, we are trying to access a member of the class (getting the value of a property) only if the object is null. To simplify this operation, the C# language provides the null-conditional operator represented as ?. (the question mark immediately followed by a period). To apply it, use it to access the member of a class. Here is an example:

int ? beds = 0;
House habitat = null;
Description desc = new Description();

beds = habitat?.Bedrooms;

Here is another version of the code:

int ?beds = -1;
Description desc = new Description();
House habitat = new House();
habitat.Bedrooms = 5;

beds = habitat?.Bedrooms;

The ?. operator checks whether the variable on its left is currently holding a null value. If it is, nothing happens. If it doesn't, then the member on its right is accessed and the operation that must be performed proceeds.

The Null Coalescing Operator

The ?. operator is used to simply check the nullity of a variable. You must apply the subsequent statement separately. To make it possible to combine the ?. operation and its subsequent statement, the C# language provides the null coalescent operator represented as ?? (Two question marks). To apply it, type it after the condition followed by the desired statement. Here is an example:

int ?beds = -1;
Description desc = new Description();
House habitat = null;

beds = habitat?.Bedrooms ?? 0;

This code states that if the House object is null, the beds variable should be assigned 0. If the House object is not null, then the beds variable should receive a value from the designated property of the House class:

int ?beds = -1;
Description desc = new Description();
House habitat = new House();
habitat.Bedrooms = 5;

beds = habitat?.Bedrooms ?? 0;

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, FunctionX Next