I suggest we ...

Override `ToString` for discriminated unions and records

It's a pain and dirty to add `override x.ToString() = sprintf "%A" x` to every type in order to make `String.Format()` happy:

type T1 =
{ Id: int
Version: string }
override x.ToString() = sprintf "%A" x

type DU =
| C1 of int
| C2
override x.ToString() = sprintf "%A" x

I think it's very easy to teach the compiler generate this override automatically for all user types.

181 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Vasily Kirichenko shared this idea  ·   ·  Admin →

    4 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • exercitus vir commented  · 

        I am against this. ToString() carries no semantics. To what kind of string? Is it an atomic value or structured value? Is it for logging or display to the user? There is no consistency. The ToString() method should simply be deprecated.

        You can always simply call sprintf "%A" any structural type to get a good structured representation even if its very slow.

      • Matthew Peacock commented  · 

        However, %A is very very slow, ideally the implementation should not do any reflection at runtime, but be based on code generated at compile time.

      • Steffen Forkmann commented  · 

        Also it's hard to debug such types without the automatic tostring implementation. Debugger just shows the type name.

      F# Language

      Feedback and Knowledge Base