Skip to content

Single tilde ~ in expressions compiles, but shouldn't #16135

@brianrourkeboll

Description

@brianrourkeboll

Using the .NET 7 SDK and above, a single tilde ~ can be used in nearly any expression context and will compile (and can even make otherwise nonsensical syntax compile), but such an expression will fail or behave unintuitively at runtime.

Repro steps

  1. Put a single tilde ~ in nearly any expression context: prefix, infix, postfix, circumfix...
  2. The code compiles, but either:
    a. Fails at runtime with a System.NullReferenceException.
    b. Fails at runtime with Fatal error. Internal CLR error. (0x80131506), which crashes the runtime altogether. Exciting!
    b. Generates a default value (0, null, etc.)—neat shorthand for Unchecked.defaultof<_>!
// These all compile...
let f x = ~x
let g x y = x ~ y
let h x y = (x ~) y
let p x = x~
let q x = x ~
let x : int = ~
let _ : int = ~ ~ ~ ~
let _ = ~1
let _ = 1~
let _ = ~1~
let _ = (~) 1
let _ = (~) 1 1 1 1
let _ = ~ 1 1 1 1
let _ = 1 1 1 1 ~
let _ = 1 1 ~ 1 1
let _ = ~ DDD ~
let _ = ~ _._. ~
let _ = ~ ``(👉゚ヮ゚)👉`` ~
let _ = ~ <int> ~
let () = ignore ~
let zero = ~ + ~

Expected behavior

I don't believe that any code using a single ~ should compile (prefix operators involving ~ always have at least one other character).

Actual behavior

The code compiles—including outlandish code that would otherwise never compile—and strange things happen at runtime.

Known workarounds

Don't accidentally type ~ anywhere.

Related information

This behavior happens for me when compiling with the .NET 7 and 8 SDKs, but not with .NET 6, so it seems likely that it was introduced in 7.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugImpact-High(Internal MS Team use only) Describes an issue with extreme impact on existing code.Regression

    Type

    No type

    Projects

    Status

    Done

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions