Shortcut Formatting: A feature request for C# vNext!
January 10, 2008
I’ve been pondering what possible features could be added to C# after version 3.5 of the compiler. For sure things like parallelism constructs are on the radar for the language team at Microsoft, but while they are at it I would like them to tackle a simpler challenge as well – a shortcut for formatting strings.
Let’s say that my code is going to throw and exception, I typically need to build the error message to load into the exception message. That could be expressed as:
throw new Exception(string.Format(”{0}{1}{2}”, a, b, c));
But I think we could have a nicer inline string format syntax:
throw new Exception( @(”{0}{1}{2}”|a|b|c) );
I’m not sure about the syntax, but the idea is a more compact syntax that would look good inline, especially if you had nested object constructions, like a LINQ projection.
January 10, 2008 at 4:28 am
um… dude, that’s horrible… just do ruby strings plz…
throw new Exception(”{a}{b}{c}”);
surely compiler can retwire it to String.Format()… if MS needs some help, I already have C# code to do just that
January 10, 2008 at 4:53 am
The String.Format in your example is a little verbose but it really gets out of hand when you start playing ball with Code Analysis rule CA1305:
String.Format(CultureInfo.CurrentCulture, “{0}{1}{2}”, a, b, c);
Not sure how I’d work the IFormatProvider into your shortcut notation.
January 10, 2008 at 7:34 am
mmm… I don’t know about this one, why add the “|” character in there?
I ended up writing my own post
January 10, 2008 at 7:40 am
[...] vNext wishlist: comma less argument list Mitch Denny has a post about his feature request for the next version of C#he wants to have a shortcut to format strings, [...]
January 10, 2008 at 9:38 pm
Ruby’s simplicity might be a good guide:
throw new Exception(”{a} {b} {c}”);
January 14, 2008 at 10:32 am
[...] posted about his wish to integrate a shortcut for formatting in c# vnext. Let’s say that my code is going to throw and exception, I typically need to build the error [...]
January 20, 2008 at 10:36 pm
All good feedback. I think I like the parameter substitution approach the best e.g.:
“{a}{b}{c}”
Having said that I think that the string would need a suffix so that the compiler knew to interpret it differently, for example:
@@”{a}{b}{c}”
Then, you could also use standard format string syntax as well to format the parameters:
@@”{a:c}[b}{c}”
February 21, 2008 at 9:31 am
[...] this year Mitch suggested a string formatting syntax for C# vNext. His suggestion was that string.Format could be replaced with syntax like [...]
March 14, 2008 at 5:31 am
[...] que quisiera ver en la siguiente version de C# Mitch Denny escribio sobre lo que el quisiera para la siguiente version de C# (mucha otra gente ha escrito sobre este [...]