Dark Mode

Nick Van Exan

Software Developer

Backing Fields

Resolving null reference errors for new properties in existing CosmosDB documents

I learned a quick trick this week re how to resolve null reference errors when you add new properties to an existing CosmosDB document class. Let's say you have an existing BaseEntity class that needs two new properties added for CreatedDate and CreatedBy. If you add those properties to your class definition, you'll get null reference errors for your existing data that is missing those properties. But you can fix the issue with backing fields like so...

public abstract class BaseEntity {

    // … other existing props

    public DateTimeOffset CreatedDate { get => _createdDate ?? new DateTimeOffset(); set => _createdDate = value; }

    private DateTimeOffset? _createdDate;

    public string CreatedBy { get => _createdBy ?? string.Empty; set => _createdBy = value; }

    private string? _createdBy;

}

July's Fragments

All fragments