You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中重写List<T>的Add方法以检查列表空值的可行性与语法

How to Safely Add Elements to a List Property Without Repeated Null Checks

Your approach with the dedicated Add method is totally valid—it encapsulates the null check so you don’t have to repeat that logic everywhere. But there are even cleaner, more idiomatic ways in C# to ensure your Notes list is never null in the first place, which removes the need for null checks entirely. Here are the most common solutions:

1. Initialize the List in the Class Constructor

The simplest and most straightforward fix is to create the List<Note> instance when the MyClass object is constructed. This guarantees Notes is never null, no matter how it’s used later:

public class MyClass
{
    public int MyClassID { get; set; }
    public List<Note> Notes { get; set; }

    public MyClass()
    {
        // Initialize the list immediately
        Notes = new List<Note>();
    }

    // Optional: Keep your Add method if you want to encapsulate additions
    public void Add(Note note)
    {
        Notes.Add(note); // No null check needed anymore!
    }
}

Now even if someone writes someClass.Notes.Add(newNote) directly, it will work without throwing a null reference exception.

2. Use Lazy Initialization with a Backing Field

If you prefer the list to only be created when it’s first accessed (lazy initialization), you can use a backing field with the null-coalescing assignment operator (??= available in C# 8.0+):

public class MyClass
{
    private List<Note> _notes;

    public int MyClassID { get; set; }
    public List<Note> Notes
    {
        get => _notes ??= new List<Note>(); // Initialize if null, then return
        set => _notes = value;
    }

    // Your Add method remains safe, and direct access to Notes is now safe too
    public void Add(Note note)
    {
        Notes.Add(note);
    }
}

This way, the list is only instantiated the first time it’s referenced, which can be useful if the list is rarely used and you want to save a tiny bit of memory upfront.

3. Stick with Your Encapsulated Add Method (With a Guard)

Your original approach works, but it has a caveat: if other code directly accesses someClass.Notes instead of using your Add method, it could still hit a null exception. To mitigate this, make the Notes property’s setter private so external code can’t set it to null:

public class MyClass
{
    public int MyClassID { get; set; }
    public List<Note> Notes { get; private set; } // Private setter prevents external null assignment

    public void Add(Note note)
    {
        if (Notes == null)
            Notes = new List<Note>();
        Notes.Add(note);
    }
}

For extra safety, combine this with constructor initialization (as in option 1) and you can remove the null check in the Add method entirely.

Bonus: Use Nullable Reference Types (C# 8+)

If you’re using C# 8 or later, enabling nullable reference types will help the compiler catch potential null issues early. Mark your Notes property as non-nullable, and the compiler will warn you if you forget to initialize it:

#nullable enable
public class MyClass
{
    public int MyClassID { get; set; }
    public List<Note> Notes { get; set; } // Compiler warns if not initialized

    public MyClass()
    {
        Notes = new List<Note>(); // Fixes the warning
    }
}

Summary

The best practice is to eliminate the null state entirely—either by initializing the list in the constructor or using lazy initialization with a backing field. This way, you never have to write null checks when adding elements, whether you use a dedicated Add method or access the list directly.

内容的提问来源于stack exchange,提问作者dvo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:36:49