My C# Wish List

I really like C#, but I wish there were a bit more to the language. The Visual Studio team has set up a UserVoice page so you can vote on your own favorites. I have placed some votes already, but here’s what I’m wanting:

String Interpolation

var userName = "ChrisMissal";
var someString = "Hello, my name is $(userName), nice to meet you!";

var a = "Now is $(DateTime.Now).";
var b = "Tomorrow will be $(DateTime.Now.AddDays(1))";
var c = "This list has $(list.Count()) items.";

I want something like this mostly because I hate writing string.Format and/or creating .Format() type extension methods.

Overriding the ?? Operator

I would love to be able to override/extend the null-coalescing operator (??) in C#. This way “string like” objects could combine checks for null, empty, whitespace, etc. Like anything, I’m guessing this could be abused if not used properly. Also, I know I’ve wanted to do this, but can’t come up with a good example to share. I know others have thought that this would be helpful, anybody willing to share an example?

“Anonymous Tuples”

I don’t know what this is actually called, but I’d like to write this code in some instances:

// I want to be able to do this in C#

int a = 4;
int b = 2;

(a, b) = (b, a); // swap values

// ... and used in some terribly named methods...

public void AssignValues()
{
    var (id, name) = GetValues();
    // more statements
}

public int, string GetValues()
{
    return (123, "gist");
}

I think this could make things cleaner and easier to read in several circumstances.

Related:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Chris Missal

Oh hey, I'm a Senior Consultant for Headspring in Austin, TX. I've been working in software professionally since 2006 and I really, really love it. I'm mostly in the Microsoft world, but enjoy building computer things of all sorts (to be vague). When I'm not slinging code, I'm probably out and about slinging discs, bowling balls, or good beer with great friends.
This entry was posted in C# and tagged , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • SHODAN

    Very Perlish.

  • Name My Tuples

    I’d like to see naming of a Tuple’s elements (rather than having to use Item1, Item2 etc.).

    My pet hate is having to do this:

    var myTuple = new Tuple(1, “Frank”);
    var iHateThisBit = myTuple.Item1;

    • http://twitter.com/noel_kennedy Noel Kennedy

      You can have c# infer the type here :

      var tuple =  Tuple.Create(1, “Frank”);

      Will still need to refer to Item1 though :(

  • http://twitter.com/pauldendulk Paul den Dulk

    I vote for Anonymous Tuples. It would make lots of geometry code cleaner:
    var x, y = SomeTransform(x, y)
    No need to define another Point class for another library.

  • Rich OKelly

    I like the anonymous n-tuples idea – the Item1, Item2,… properties are cumbersome to type and IMHO hinder readability. Although in your example, I’d find the following syntax for methods returning tuples clearer:

        
    public (int, string) GetValues() Which, although potentially horrific, allows for tuples containing tuples themselves to be expressed consistently:         public (int, (
    int , string)) GetValues() I believe that F# also already has this notation for tuples, so the necessary compiler tricks for this feature already exist. Which, one would hope, would reduce the necessary work required for this to be included in a future version of C#.I like the idea of being able to overload*  the null coalescing operator (for instance to be able to mimic the truthy and falsey nature of objects in javascript), however I can’t see enough people having valid use cases for the feature to make it worthwhile – in both of our examples the conditional opertaor (?:) is sufficient without necessarily harming readability.* Not override. No operators are currently ‘virtual’ – I would imagine the work required to make operators overrideable would be complex and almost certainly a breaking change.Personally, I’d be against the string interpolation. String formatting can be hard, there are many languages with different formatting rules. Would this feature be limited only to one (the invariant) culture? What would the syntax be that is backwards compatible with strings written in all programs since C# 1 everywhere in the world? How is this string formatting internationalisable – do you have to have the variable names in the resources?

  • http://twitter.com/noel_kennedy Noel Kennedy

    I would love to be able to override the  ?? and ? operators.  It would be really useful for monads, for example: 
    Option x = //get from somewhere  var t = x ?? “Default”;

    vs x.GetOrElse(“Default”);

    Or if expressions using the ternary operator:  

    check ? “Value”.ToSome() : Option.None();
    currently won’t compile because ternary operator requires both expressions to return same type and ToSome() returns Some and Option.None() returns None

    Not sure whats going on with the formatting here, but I think you will get the gist!

  • Anonymous

    Also, an unless keyword, instead of having if (!condition) clauses.

  • Anonymous

    Yes, an ‘unless’, overriding ?? and tuple unpacking (your anon tuple http://docs.python.org/release/1.5.1p1/tut/tuples.html) also can I get ‘list comprehensions?’ 
    http://www.secnetix.de/olli/Python/list_comprehensions.hawk

  • Guest

    I wish there was an operator that could be used in a way to reduce null checks when traversing an object model.

    var x = ?foo.Bar.Baz.X.Y.Z;

    ‘x’ would be null if any of the properties in the chain was null; otherwise ‘x’ would be the value/pointer of Z.

    Currently you have to write:

    private ZType GetZ(FooType foo){
    if(foo==null)
    return null;

    if(foo.Bar == null)
    return null;

    if(….)

    }

    When you consume 3rd party API’s you are at the mercy their developers caring about demeter.

    • Anonymous

      Ah man, I just posted this. Existenial operator!

    • http://twitter.com/MonocularVision Michael McGuire

      I Instapaper’ed this blog entry to post this very feature request later, but you beat me to it. I find the null coalescing operating to be basically useless, as I typically want to read some property off an object reference but have to check the object reference first.

  • Łukasz Drynkowski

    String Interpolation is a terrible idea, just think about refactoring. I say no to magic strings!

    • Chris Missal

      ReSharper can handle things like this.

      • Sam

        You could use some other operator in front of the string. Like @ changes the behaviour of a literal perhaps another operator could enable string interpolation. No breaking change that way

        • http://chrismissal.lostechies.com Chris Missal

          Definitely. Or use something other than double quotes too. Powershell allows for single and double quotes, but interpolation only occurs when using the double quotes.

    • Chris Bristol

      The compiler is going to need to do some sort of transform on the string anyway, so it can easily (and arguably should) check to be sure that the expression inside the $(…) block is valid. I think the biggest resistance for such a feature is that it is a breaking change; any program which contains a string to be printed of the form $(…) would be broken.

  • Anonymous

    How about the CoffeeScript/Ruby idea of existential operator? I could use that a ton!

    Today:

    var someVar = MyClass.MayNotExist();

    if (someVar != null && someVar.CouldBeNull != null) {
        return someVar.CouldBeNull.SomeProp;
    }
    return null;

    Tomorrow:

    return MyClass.MayNotExist?().CouldBeNull?.SomeProp;You get the idea.

    http://coffeescript.org/#operators

  • http://devtalk.net Dmitri

    #3 is definitely a must (F# rules), #2 is somewhat dubious but there are cases when it’s useful to override any operator (again, in F#). As for #1, this string splicing can be done via a refactoring tool (e.g., this ReSharper Plugin), but this refactors a PHP-like statement into a string.Format() call. Still, better than nothing, eh?

  • http://blog.usepowershell.com/ Steven Murawski

    Two of the three are native capabilities in PowerShell (string interpolation and anonymous tuples) and that always trips me up moving between PowerShell and C#

    • http://chrismissal.lostechies.com Chris Missal

      In all honesty, working a bit in PS is where some of these came from.

  • http://larud.myopenid.com/ Rudi

    Do all of these new features sound like Roslyn ‘extensions’ of some sort?

    I mean, once roslyn is available in the language (C#5?) could these be build as ‘nuget-able’ extensions in your project?

    Personally I’d rather prefer to keep C# lighter and have a ‘pick-and-choose’ way to include  language features. 

    e.g. I would not favour the ‘unless’ statement. Just refactor the if (!condition) to an if (ReverseCondition())

  • Anil

     Example provided in “String Interpolation” section is present in PHP. But don’t know why microsoft has not yet introduced such kind of feature in .Net

  • http://piranout.ps.cm Paul Smith

    The string tokenizing feature you describe would definitely be extremely useful. Implementing it in/on the string class itself could be very problematic though. I think the idea is a great candidate for a ‘TokenString’ type struct with overloaded implicit conversion operators to/from String that behave the way you describe. 

  • Michael Robin

    A reasonable typle syntax and tuple-unpacking/destructuring/assignment is useful and a good core language feature – and agree about something like a?.b?.c?.c — this is a pain every programmer deals with every day.
    Other customizations like your syntax-embedding/string interpolation could be handled by making C# a better langage for meta-programming, so that your own DSL can be implemented within C# without writing seperate native code extensions, etc.