Skip to content

[Proposal] Null-coalescing Assignment Operator: ??= #205

@judemelancon

Description

@judemelancon

??= would have semantics analogous to the existing compound assignment operators like +=, %=, and <<=. More precisely, x ??= y would be equivalent to x = x ?? y except that x is evaluated only once. It would have clear, if not vast, utility. Hopefully, it would not be an unreasonably large effort.

It is perhaps debatable whether

object o = GetFirstChoice( foo, bar, someLongArgument )
         ?? GetSecondChoice( foo, bar, someLongArgument )
         ?? GetFallback();

looks better than

object o = GetFirstChoice( foo, bar, someLongArgument );
o ??= GetSecondChoice( foo, bar, someLongArgument );
o ??= GetFallback();

However, the latter seems easier to step through in the debugger.

Furthermore, a use case like

private static void ApplyNewSettings( SettingsSource newSource ) {
    // Set each setting if and only if it is not already set to a non-null value.
    // This could be e.g. applying defaults after deserializing user settings.
    this.SomeSetting ??= newSource.SomeSetting;
    // ...
}

is less repetitive with ??=.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions