Thursday, January 5, 2023
HomeITThe way to use the null object sample in .NET

The way to use the null object sample in .NET


You may typically encounter null reference exceptions in your functions if null checks aren’t appropriately carried out. A null reference exception will abruptly terminate the execution of your program except it’s correctly dealt with in your code. The null object sample solves this downside, providing you with a chic option to deal with null reference exceptions in your code.

This text discusses how we are able to implement the null object sample in C# with related code examples wherever relevant. To work with the code examples offered on this article, it’s best to have Visible Studio 2022 put in in your system. For those who don’t have already got a replica, you’ll be able to obtain Visible Studio 2022 right here.

Create a console software venture in Visible Studio

First off, let’s create a .NET Core console software venture in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined under to create a brand new .NET Core console software venture.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new venture.”
  3. Within the “Create new venture” window, choose “Console App (.NET Core)” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new venture” window proven subsequent, specify the identify and placement for the brand new venture.
  6. Click on Subsequent.
  7. Within the “Further data” window, select “.NET 7.0 (Commonplace Time period Assist)” because the Framework model you want to use.
  8. Click on Create.

We’ll use this .NET Core console software venture to work with the null object design sample within the subsequent sections of this text.

What’s the null object sample?

The null object sample is a behavioral software program design sample that’s used to encapsulate the dealing with of null values in an object-oriented programming language. It’s used to assist enhance code readability and maintainability by eliminating the necessity for express null checks.

The null object sample defines an summary class that represents a null worth. A concrete subclass is then created that inherits from the summary class and offers concrete implementations for all the strategies. This concrete subclass is then used all through the code base at any time when a null worth must be represented.

Why use the null object sample?

There are a variety of causes to make use of the null object sample when working with objects in C#. First, it could actually assist to keep away from null reference errors. Second, it could actually make code extra readable by avoiding checks for null values. Third, it could actually enhance efficiency by avoiding pointless calls to strategies and properties. Lastly, it could actually make it simpler to unit check code.

Implementing the null object sample in C#

To implement the null object sample in C#, we’ll observe the three steps outlined under.

  1. Outline an interface or an summary class.
  2. Present concrete implementations of the strategies of the summary class or the interface in a category that extends both of them.
  3. Outline a null implementation by overriding the strategies of the summary base class or the interface and returning acceptable values on your null object.

Create an summary class in C#

Within the console venture created earlier, create a category referred to as AbstractProduct, delete the default generated code, and enter the next code.

 
public summary class AbstractProduct
{
    public summary int Id { get; set; }
    public summary string Identify { get; set; }
    public summary string GetProductDetails();
}

Implement strategies of the summary class in C#

Subsequent, create one other new class named Product in a file named Product.cs. Delete the default generated code and enter the next code as an alternative.

 
public class Product : AbstractProduct
{
    public override int Id
    {
        get;
        set;
    }
    public override string Identify
    {
        get;
        set;
    }
    public override string GetProductDetails()
    {
        return $"Product Id: {Id}, Product Identify: {Identify}";
    }
}

Implement a category to deal with null values in C#

Create a category named NullProduct to deal with null values, delete the default generated code, and enter the next code.

 
public class NullProduct : AbstractProduct
{
    public override int Id
    {
        get;
        set;
    }
    public override string Identify
    {
        get;
        set;
    }
    public override string GetProductDetails()
    {
        return $"Product Identify: {Identify}";
    }
}

Full our null object sample instance in C#

Lastly, we’ll create the ProductRepository class used to work with the product information of our instance software. ProductRepository accommodates a technique named GetProduct that accepts the product ID as a parameter and returns both a product occasion (if the product is discovered) or an occasion of NullProduct if no product is discovered.

 
public class ProductRepository
{
    Listing<Product> merchandise = new Listing<Product>();
    NullProduct? NotFound = new() { Id = -1, Identify = "Not Accessible" };
    public ProductRepository()
    {
        merchandise.Add(
            new Product()
            {
                Id = 1,
                Identify = "DELL Laptop computer"
            });
        merchandise.Add(
            new Product()
            {
                Id = 2,
                Identify = "Lenovo Laptop computer"
            });
    }
    public AbstractProduct GetProduct(int id)
    {
        AbstractProduct product = merchandise.Discover(x => x.Id == id);
        return product ?? NotFound;
    }
}

Execute the appliance

Now, use the next piece of code to retrieve a product occasion and name the GetProductDetails technique to get the main points in regards to the product, if one is discovered.

 
ProductRepository productRepository = new ProductRepository();
var product = productRepository.GetProduct(1);
Console.WriteLine(product.GetProductDetails());

Determine 1 reveals the output.

null object pattern example 01 IDG

Be aware that, as a result of the product ID (1 on this case) is on the market within the record of merchandise, the product particulars (DELL Laptop computer) are displayed. Now let’s go a product ID that doesn’t exist because the parameter to the GetProduct technique, as proven within the code snippet given under.

 
ProductRepository productRepository = new ProductRepository();
var product = productRepository.GetProduct(3);
Console.WriteLine(product.GetProductDetails());

This time, the product is not going to be discovered and an acceptable message will likely be displayed on the console window as proven in Determine 2.

null object pattern example 02 IDG

The null object design sample helps you keep away from potential null reference exceptions, simplifies your code, and reduces the quantity of litter that’s related to conventional strategies for dealing with null values. By utilizing a null object in lieu of a null worth you’ll be able to keep away from runtime exceptions elegantly, and make your code simpler to take care of in the long term.

Copyright © 2023 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments