csharplang/meetings/2017/LDM-2017-08-16.md
2018-01-25 13:11:49 -08:00

2.4 KiB

C# Language Design Notes for Aug 16, 2017

Quote of the day:

"It's an open question whether we go out with a bang!"

Agenda

  1. The null-forgiving operator

The null-forgiving operator

How exactly does the null-forgiving post-fix ! operator work?

Proposal:

  1. Target typed: e! implicitly converts to T if e does, but without nullability warnings
    • string s = null!;
    • string s = default!
    • string s = GetNameOrNull()!;
    • List<string> l = GetList<string?>()!;
    • List<string?> l = GetList<string>()!;
  2. Inherent type: if the type of e is a nullable reference type T?, then the inherent type of e! is T
    • var s = GetNameOrNull()!;
    • GetNameOrNull()!.Length;
  3. Default expressions: if T is a non-nullable reference type, then default(T)! suppresses the warning normally given by default(T)

For 2, an alternative is to have a dedicated !. and ![...] operator, cousins of ?. and ?[...]. Then you wouldn't get to factor out to a local with var, though.

3 is a bit of a corner case. Most people would choose to just rewrite it to something else - there are plenty of options. But default(T) is a good strategy for code generators, so probably worth keeping the ability to silence that warning.

We could generalize ! to silencing all nullability warnings even in subexpressions. This seems ill-motivated, though, and there's no particular expectation that you want silencing in subexpressions at the same time you want it on the overall expression.

If ! is applied in a place that yields no nullability warnings, does that lead to a warning? No. We don't want to create a new source of warnings caused by a warning-suppressing operator! There is a legit scenario, which is to clean up superfluous "!"s when a depended-upon API gets properly annotated. But this seems more the province of analyzers or similar tools.

We can make !! an error. If you really want two consecutive bangs (we don't believe there's any scenario, other than swearing) you can parenthesize: (e!)!.

An alternative is to make the type of e! oblivious, if we choose to embrace a notion of oblivious. That's attractive in that it makes a type for "something that doesn't yield warnings", but it's also viral - could lead to many things not being checked. It's an option to be considered in future.

Conclusion

Follow the proposal. Make !! an error.