Skip to content

Warn about incorrect use of default in ternary operator #848

@bash

Description

@bash

I just ran into a footgun with our implicit option constructor:

The following snippet does not return an empty option but a some-option with a default-initialized tuple inside:

Option<(string, int)> DefaultUsage(bool cond) => cond ? ("hello world", 42) : default;

This of course applies to all value types:

Option<int> DefaultUsage() => false ? 42 : default; // returns Some(0), not None.

for reference types, we get at least a nullable warning:

Option<string> DefaultUsage() => false ? "hello world" : default;
//                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// warning CS8604: Possible null reference argument for parameter 'item'
// in 'Option<string>.implicit operator Option<string>(string item)'.

We should emit a warning in these cases:

  • default inside ternary inside implicit conversion to Option
  • default inside switch expression inside implicit conversion to Option
  • others?

This is of course perfectly fine and returns None as expected:

Option<(string, int)> DefaultUsageFine(bool cond)
{
    if (cond) { return ("hello world", 42); }
    else { return default; }
}

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