Skip to content

[API Proposal]: NullReferenceException.ThrowIfNull #130489

Description

@MichalPetryka

Background and motivation

Some code needs to throw NullReferenceException instead of ArgumentNullException, either for performance or compatibility reasons.

Currently the code relies on using weird patterns to trigger that, which is both not nice to write and obscures the intent of code, introducing need for comments.

Introducing an explicit way to trigger a nullcheck would make the code clearer to any reader.

The check would be implemented using a dereference by runtime, so invalid pointers would cause an AccessViolationException.

API Proposal

namespace System;

public class NullReferenceException
{
    public static void ThrowIfNull(object i);
    public static void ThrowIfNull(void* ptr);
    public static void ThrowIfNull<T>(ref readonly T r);
}

API Usage

NullReferenceException.ThrowIfNull(obj);
NullReferenceException.ThrowIfNull(ptr);
NullReferenceException.ThrowIfNull(ref r);

Alternative Designs

People can continue doing the obscure current variants:

_ = obj.field; // needs to know the type
_ = Unsafe.ReadUnaligned<byte>(ptr); // Null pointers are UB in C#.
_ = Unsafe.ReadUnaligned<byte>(ref Unsafe.As<T, byte>(ref r)); // Roslyn optimizes out unused derefs.

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions