Probable C# 6.0 features illustrated

  • šŸ“…
  • šŸ“ 883
  • šŸ•™ 4
  • šŸ“¦ .NET
  • šŸ’¬ 79

C# 6.0 is now available and the final list of features is well explainedĀ by Sunny Ahuwanya so go there and try it with his interactive samplesĀ page.

Adam Ralph has a list of the probable C# 6.0Ā features Mads Torgersen from the C# design team coveredĀ at new Developers Conference() NDC 2013 inĀ London.

I thought it would be fun to show some before and after syntax for comparison and in doing so ended up with a few thoughts andĀ questions.

1. Primary Constructors

Shorter way to write a constructor that automatically assigns to private instanceĀ variables.

Before

public class Point {
  private int x, y;

  public Point(int x, int y)
    this.x = x;
    this.y = y;
  }
}

After

public class Point(int x, int y) {
  private int x, y;
}

Thoughts

  • Do you need to independently define x andĀ y?
  • Can you still write aĀ body?
  • How would you make the defaultĀ private?

This solution feels too constrained, would have preferred somethingĀ like:

  public Point(set int x, set int y)

That set the property and optionally created a private one if it didnā€™t. Would allow bodies, use on multiple constructorsĀ etc.

2. Readonly autoĀ properties

Readonly properties require lessĀ syntax.

Before

private readonly int x;
public int X { get { return x; } }

After

public int X { get; } = x;

Thoughts

  • Love this.
  • Very useful for immutableĀ classes.

3. Static type usingĀ statements;

Imports all the public static methods of a type into the currentĀ namespace.

Before

public double A { get { return Math.Sqrt(Math.Round(5.142)); } }

After

using System.Math;

public double A { get { return Sqrt(Round(5.142)); } }

Thoughts

  • Not something Iā€™ve run into often but no doubt very useful for Math-heavyĀ classes.
  • Could be useful for Enumerable LINQ-heavy classes if it works with static extensionĀ methods.

4. Property Expressions

Allows you to define a property using a shorthandĀ syntax.

Before

public double Distance {
  get { return Math.Sqrt((X * X) + (Y * Y)); }
}

After

public double Distance => Math.Sqrt((X * X) + (Y * Y));

Thoughts

  • Small but useful syntaxĀ reduction.
  • Has nothing to do with System.Linq.Expression despite theĀ name.

5. Method Expressions

Allows you to define a method using a shorthandĀ syntax.

Before

public Point Move(int dx, int dy) {
  return new Point(X + dx1, Y + dy1);
}

After

public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);

Thoughts

Same as PropertyĀ Expressions.

6. Params forĀ enumerables

No longer need to define your params methods as an array and force early evaluation of theĀ arguments.

Before

Do(someEnum.ToArray());
public void Do(params int[] values) { ... }

After

Do(someEnum);
public void Do(params IEnumerable<Point> points) { ... }

Thoughts

  • Can have params methods for IEnumerable and array side-by-side? ProbablyĀ not.
  • Is evaluation deferred until evaluated if you pass a single IEnumerable instead of aĀ params?

7. Monadic nullĀ checking

Removes the need to check for nulls before accessing properties or methods. Known asĀ the Safe Navigation Operator inĀ Groovy.

Before

if (points != null) {
  var next = points.FirstOrDefault();
  if (next != null && next.X != null) return next.X;
}
return -1;

After

var bestValue = points?.FirstOrDefault()?.X ?? -1;

Thoughts

Love it. Will reduce noise in code and hopefully reduce null reference errorsĀ everywhere!

8. Constructor type parameterĀ inference

Removes the need to create static factory methods to infer generic types. This is helpful with TuplesĀ etc.

Before

var x = MyClass.Create(1, "X");

public MyClass<T1, T2> Create<T1, T2>(T1 a, T2 b) {
    return new MyClass<T1, T2>(a, b);
}

After

var x = new MyClass(1, "X");

Thoughts

  • Another great addition.
  • Does it understand list and collection initializers to automatically determine the generic typesĀ too?

9. Inline declarations for outĀ params

Lets you declare the out variables inline with theĀ call.

Before

int x;
int.TryParse("123", out x);

After

int.TryParse("123", out int x);

Thoughts

  • Not a particularly large syntaxĀ reduction.
  • Shorter code for Try methods andĀ DirectX.

Wrapping up

Hopefully there are a few more gems to come that would help reduce noise. Would especially like to see syntax that wired up an interface to an internal instance variable where not specifically overridden to aid in encapsulation,Ā e.g.

public MyClass : IList =&gt; myList {
  private IList myList;

  public Add(object item) {
    // Do something first
    myList.Add(item);
  }
}

[)amien

79 responses to Probable C# 6.0 features illustrated

  1. Avatar for

    Information is only used to show your comment. See my Privacy Policy.

  2. Avatar for Pavel

    WriteLine(Ā«Welcome to my version of Roslyn!Ā»);Ā ā€” Nothing terrible everĀ seen! Give then add another denotation of theĀ brackets: WriteLine(<>); And maybe even add aliases for commandĀ localizations: alias Š—Š°ŠæŠøсŠ°Ń‚ŃŒŠ”трŠ¾Šŗу =Ā WriteLine; .. Š—Š°ŠæŠøсŠ°Ń‚ŃŒŠ”трŠ¾Šŗу(<>);

    Until the anounce date of sixth version of the C# language shownĀ promise. Most who picked the language wishes to develop their program in ā€œC++"-like programmingĀ language. Programmers who are wishing to use Scala or F# are very-veryĀ few! Instead of optimizing the compiling code and improve the quality of the language it was created another piece ofĀ trash.

    int X=>x*x;
    int X {get {x*x;}};
    var x=(var y=rand(10);y*y);
    

    And it increases the readability of theĀ programā€¦

    public double Distance => Math.Sqrt((X * X) + (Y * Y));
    

    At a first glance it might be confused with theĀ delegate

    Indexed member initializer:

    new JObject { $x = 3, $y = 7
    

    and indexed memberĀ access

    c.$name = c.$first + " " + c.$last;
    

    It generally looks like a failed attempt to realize the potential ofĀ DLR. The next step will probably be theĀ following:

    var n = "name";
    c.$(n) = c.$("first") + " " + c.$last;
    

    But on the other hand, if field values will be stored in dictionaries within the class, then this programming language is generally not necessary. We can use JavaScript. His speed will then be theĀ same.

    NameOf operator:

    string s = nameof(Console.Write);
    

    Although perhaps will finally something useful. If you do not think that there are betterĀ implementation..

  3. Avatar for Matthijs Wessels
    Matthijs Wessels

    Looks great. For #1, I like the way TypeScript has doneĀ this:

    public class Point {
        public Point(private int x, public int y, int z)
        // other initialisation using z.
    }
    
  4. Avatar for AsbjĆørn Ulsberg

    I love most of this, but the proposed syntax for readonly auto-properties is -- pardon my french -- butt ugly! Why not use the alreadyĀ existing readonly keyword?

    public readonly int X { get;Ā }

  5. Avatar for Wouter

    Values. Like var but cannot beĀ changed.

    val five = 5;
    five = 6; // Causes error
    

    Currently itā€™s impossible to forceĀ this.

  6. Avatar for Leon

    I hope none of this makes it to C#Ā 6.0.

    I am OK withĀ 7

    by quickly looking at 8 scrolling through code you might make the mistake to think you are making an instance of a non-genericĀ class. By using the ā€˜varā€™ keyword you also hide the fact that it isĀ actually MyClass and not MyClass

    var x = new MyClass(1, "X");
    var y = new MyClass("x", 1);
    

    x and y are not compatible with eachĀ other.

    I guess 8 is OK if the programmers use it likeĀ this:

    MyClass x = new MyClass(1, "X");
    MyClass y = new MyClass("x", 1);
    
  7. Avatar for Jenda

    To John Bergman:

    public static bool In(this T obj, params T[] list) {
        return list.Contains(obj);
    }
    ..
    if (x.In(3,6,8,12)) { ..
    }
    
  8. Avatar for Jenda

    I do hope the #2 doesnā€™t makeĀ it!

    The point is ā€¦ this syntax is confusing and would be better used for something different, for property with automatic backing fieldĀ initialization.

    Now if you need such a property to be initialized to a different than the default value you have to do that somewhere many lines away in the constructor and if that property is static, it even has to be a static constructor with is something you are not supposed to have unless you have to according to Analyze Code inĀ VS.

    Iā€™d much ratherĀ have

    public static int Timeout { get; set; } = 100;
    

    in place of

    private static int _timeout = 100;
    public static int Timeout { get { return _timeout; } set { _timeout = value;
    

    than ā€¦ waitasecond ā€¦ what does that example actually mean?!? IsĀ the

    public int X { get; } = x;
    

    really supposed to replace the two lines above? Whatā€™s the ā€œxā€Ā then? If you really do care so much on the distinction between the property being ā€œreadonlyā€ and ā€œwith private setterā€, then whyĀ not

    public int X { get; readonly set;
    
  9. Avatar for Marcel Veldhuizen

    I would definitely like to see #6, #7, #8, but I donā€™t care much for theĀ rest. It would be nice to make it easier to create immutable classes, but Iā€™d prefer a syntaxĀ like

    public readonly int X { get;
    
  10. Avatar for NN

    Most needed features are presented in Nemerle language and MS can adaptĀ them. For instance it has get-only properties as expected to beĀ used.

    class A
    {
        public Prop : int { get; } // Public property and hidden private field
        public this()
        {
           Prop = 1; // Initialization in constructor writes to the hidden field
        }
    }
    

    And this is how simple immutable class with constructors and properties looksĀ like:

    [Record]
    class Data
    {
        public Name : string { get; }
        public MiddleName : string { get; }
        public Address : string { get; }
    }
    
  11. Avatar for Alan Bates
    Alan Bates

    One scoop of syntactic sugar that I think would be nice to have that is not on the list would be implicit var forĀ iterators. Instead of

    foreach(var entity in entities)
    

    or

    foreach(Entity entity in entities)
    

    just simply

    foreach(entity in entities)
    

    ...while still allowing the explicitĀ case

  12. Avatar for Joz

    Inline out-parameters are nice but why not take it one step further to prevent the use of out-parameters completely; allow return tuples instead like inĀ python.

  13. Avatar for Jason Bowers

    True anonymous types would be extremely helpful both in TDD and in production code. I would love to be able to quickly stub a dependency or parameter by saying var stub = new IMyInterface { value = ā€œfooā€, method => x*y }. This can work well for DTO objects, especially if they are only created and returned form only one or two linq statements, as well and encourage coding to interfaces. This is the only feature Java has that I wish C#Ā had.

  14. Avatar for Carlos Beppler
    Carlos Beppler

    Tom Tucker suggestion isĀ good. Today if you have an property that has some logic on int you must declare a private fieldĀ too. The problem is that inside the code of the class, the field can be accessed directly (without going through theĀ property). With Tuckerā€™s suggestion we can write something likeĀ this:

    public string MyProp {
        string myprop = string.Empty;
        get { return myprop; }
        set {
            if (string.IsNullOrWhiteSpace(value))
               throw new ArgumentNullException("value");
            myprop = value;
        }
    }
    
  15. Avatar for someone
    someone

    Monadic null checking is very nice, but the others are just syntax pollution. I disliked ā€œusing Mathā€ the most. Please do not introduce something like this! It has the same drawbacks as using namespace std. Methods are perfectly good wrapped intoĀ classes.

  16. Avatar for Vallarasu
    Vallarasu

    Inspired from functional programming? Most ideas sounds similar toĀ fsharp.

  17. Avatar for JoĆ£o Vitor P. Moraes
    JoĆ£o Vitor P. Moraes

    Why is that x introduced on read onlyĀ properties?

    public int X { get; } = x;
    

    Why not simply

    public int X { get;
    

    And the setter acts like a read-only attribute? The proposed syntax allows for thingsĀ like

    public int X { get; } = y;
    

    and in the constructor you wouldĀ have

    y = 5
    

    which would only bringĀ confusion

    X = 5
    

    is cleaner, simpler, and avoidsĀ confusion.

  18. Avatar for Kralizek
    Kralizek

    #6 would be more logical if instead of IEnumerable, params could be used onĀ IReadOnlyList

    And, method return typeĀ inference!

    public var GetValue()
    {
        return 1;
    }
    
  19. Avatar for David Taylor
    David Taylor

    @Dave Van denĀ Eynde

    Are you sure it doesnā€™t solveĀ it.

    obj.Maybe(obj => obj.Property);
    

    becomes

    obj?.Property
    
    obj.Maybe(ProjectionFunc);
    

    would more often become written using an extensionĀ method:

    obj?.ProjectionFunc()
    

    Or using the number 3 ā€œStatic type using statementsā€ it might beĀ written

    ProjectionFunc(obj?)
    

    Lets wait and see how all thisĀ composes.

  20. Avatar for Junior

    Suraj Deshpande is right. I felt that the syntaxes presented here are expressed as unreadable statements and they are hard toĀ maintain. Shorthands are supposed to be readable. It would be nice to write a bit more code in order to beĀ maintainable.

  21. Avatar for Dave Van den Eynde
    Dave Van den Eynde

    #7 is cool and all, but it wonā€™t make my homebrew Maybe extension method obsolete. Right now I can doĀ this:

    obj.Maybe(obj =? obj.Property);
    

    Now that would be fine if it was obj?.Property instead, but I use it more often likeĀ this:

    obj.Maybe(ProjectionFunc);
    

    I donā€™t see how this new operator would ā€œfixā€ that useĀ case.

  22. Avatar for tec-goblin
    tec-goblin

    I cannot stress enough how important what Keith Dahlby said is. I often had beautiful functional constructs that needed to use local variables just because of TryĀ methods.

    In other news, I would like to see 4 & 5 combined asĀ well:

    public ISet IdSet
    {
        get => new HashSet(ids.Split(","));
        set { ids = value == null ? null : string.join(value, ","); }
    }
    
  23. Avatar for Blair

    Have to agree with Patrick on thisĀ one.

    I do like the groovy style null checkĀ syntax.

    Algebraic data types, Higher kinded types, curried and partial function support like scala, scala style classes with primary constructors to reduce boilerplate code, type keyword for immuatable which is type checked, type aliases would be cool, enums as generic params as with integers likeĀ C++,

  24. Avatar for Patrick
    Patrick

    Itā€™s good to see C# evolving. Most of the possible changes are welcome, but I canā€™t see any true radical changes on the horizon, which for the most part is a good thing. The last thing I would want is to have C# change into some horrible C++ like language, trying to squeeze every type of programming structure into theĀ language. Iā€™ve been using C# since 2004 and feel that it has reached a maturity that wonā€™t be helped by simply adding features for very littleĀ gain.

    People wanting progress to a more advanced and robust language on the .NET platform should simply go to F#. Iā€™ve been using F# now for 3 years and I could never go back to C# as my primary problem solving language. Here is the list the goodness that F# providesĀ ā€¦

    • Immutability by default
    • Option types (eliminates nullĀ exceptions)
    • Algebraic Data Types
    • Units of Measure
    • Pattern Matching
    • Computation Expressions
    • Type Providers
    • Real nested functions
    • Proper record types
    • Non-nullable reference types
    • Value based semantics
    • Hindleyā€“Milner type inference
    • Curried functions and partial functionĀ application
    • Function in-lining
    • Succinct tuple syntax andĀ manipulation
    • Object Expressions (create interface implementations on-the-fly without a concrete classĀ implementation)
    • Elimination of uninitializedĀ variables
    • Statically resolved type parameters (aka type-safe static duckĀ typing)
    • Type synonyms/aliases
    • Type-safe string formatting

    The above features are what you need in a true 21st century programming language, and are unlikely to be incorporated into C# any timeĀ soon.

  25. Avatar for Eric Williams
    Eric Williams

    {Turns on the news} ā€œThe human race has come together and weā€™ve landed on Mars & C# still doesnā€™t have stringĀ interpolationā€

  26. Avatar for Tom R

    My idea, a FormatStringAttribute to mark methods that take format strings and then to automate variable interpolation using names instead ofĀ positions.

    Console.WriteLine("A = {0} B = {1} C = {2}", variableA, b.Property, _fieldC);
    

    Could become..

    Console.WriteLine("A = {variableA} B = {b.Property} C = {_fieldC}");
    

    No more having to keep position and argument order inĀ line.

  27. Avatar for Andrew

    I would love to see more focus on performanceĀ issues. Most of these things are frankly uselessĀ typically.

    The only relevant things to meĀ are:

    1. Better property backing syntax
    2. "Inline declarations for out params"
    3. "Params for enumerables"
    4. "Static type using statements;"

    I want toĀ see:

    • SIMD support for x86_64 and NEON
    • Auto vectorization to get closer speeds to that of C++
    • Allow pointer types without the need for an unsafe block(as a project setting)(Or add a compiler attribute that fixes structs in memory)
    • Make the base runtime OPEN SOURCE for crying out loud(like .NET Micro). This doesn't mean your frameworks need to be Open
    • More focus on RUNTIME performance, not just cold boot. Cold boot is irreverent to games, runtime performance if far more important
    • More focus on performance in the JIT period. As C# is far more productive then C++ for rapid game dev

    I would also like to see the templateĀ support. Useful for Vectors that need to be either float based or doubledĀ based.

    Also things like CPU determined types like IntPtr but for ints andĀ floats. floatx = ā€œfloat on ARM32 or double on x86_64ā€³Ā etcā€¦ intx = ā€œint on ARM32 or int64 on x86_64ā€³Ā etcā€¦

  28. Avatar for Rick

    Love the list. Will be pondering on this for some time. WhatĀ aboutā€¦

    Given:

    List myList;
    

    Perhaps:

    myList? new List {"value"};
    myList? throw new MyListNullException();
    

    or

    myList?? new List {"value"};
    myList?? throw new MyListNullException();
    
  29. Avatar for Corrie

    I like #7 most ofĀ all.

    But #1 and #9 seems like itā€™ll just cause maintainabilityĀ issues.

    At first I saw no point in thisĀ syntax:

    public int X { get; } = x;
    

    However, you need the x to exist so you can pass the property as an out or ref parameter, if that is the way you need to set it in the constructor, so I think itā€™sĀ great.

  30. Avatar for wekempf
    wekempf

    @Keith HillĀ ā€” Itā€™s ā€œkind of likeā€ but it isnā€™t, so I donā€™t think you can use unchecked here. You could use a new keyword, but new syntax might beĀ better.

    var bestValue = ?(points.FirstOrDefault().X) ?? -1;
    

    I think I prefer this over ?., because I think it would be wrong to have code likeĀ this:

    var bestValue = points?.FirstOrDefault().X ?? -1;
    

    Note I started outĀ using ?. and switched toĀ just . in that expression. I can think of no valid reason to ever do that, but it seems like an easy thing to do by mistake.Ā The ?() syntax resolves thatĀ issue.

  31. Avatar for domin8k

    My favourites are 4, 5 and 9. Iā€™m wondering if theyā€™re gonna change the proposed syntax stronglyā€¦ I really like this lambdaĀ style.

  32. Avatar for Keith Hill

    @LakshĀ ā€” I live the idea of monadic null checking but I donā€™t like the syntax. I wish we could do something likeĀ this:

    var bestValue = unchecked(points.FirstOrDefault().X) ?? -1;
    

    This is kind of like the suppression of integer overflowĀ checking.

  33. Avatar for HB

    I love 7, and actually, itā€™s the only Iā€™d like to see out of the list, no offenceĀ intended.

    3 has been supported by VB.NET forever if Iā€™m notĀ wrong.

  34. Avatar for Pete

    Would love to see extension properties, enum constraints for generics and a specification of the value type class for numbers, say, NumericValueType. Not to mention,Ā SIMD.

  35. Avatar for Laksh

    Some of the changes are good. However i think these changes will make the code less human readable. We are not writing code just for computer to understand but it should also readable by other humans. Especially 7. Monadic nullĀ checking

  36. Avatar for Damien Guard

    Iā€™m surprised at the number of people who think the syntax makes things harder to read or parse. Sure they look a little odd now but seeing a single lineĀ like:

    public int X { get; } = x;
    

    Will mean you immediately identify this is a readonly property in the future. Right now, you have to go to definition to go see what x is defined as and if it has a readonlyĀ property.

    The same is true of the safe null operatorĀ ā€” you wonā€™t have to mentally parse several ā€œif nullā€ checks just to understand it wants a property via some optionalĀ objects.

  37. Avatar for Keith Hill

    I agree with you on primary constructors. They seem oddly limited whereas something like what you proposeĀ ā€” public Point(set int x, set int y) could be used on anyĀ constructor.

  38. Avatar for Dan Sutton

    I think I like 3 onwards; 1 and 2 areā€¦ kind of weird: as though they do make sense, but donā€™t fit within the psychology of C# in some way. I think 1 is actively horribleā€¦ I can see what theyā€™re doing, but it appears to me that itā€™ll make the code very hard to parse: it might make sense to the compiler, but I donā€™t think itā€™ll make a hell of a lot of sense to the user. And if you can do that in a constructor, can you do it in a method? Logic says you should be able to. What about if you do it in a loop in the constructorā€¦? Itā€™s a bit tooĀ ambiguous.

  39. Avatar for XXXo

    @Damien : you forgot to mention the 3rd option with params : you can totally ignore it and pass nothing atĀ all.

  40. Avatar for Alan8

    I like the the Before and After examples; they make the changes veryĀ clear.

  41. Avatar for Michael Blanchet

    Talking about code noise reductionĀ ā€” I would like to see a simple ā€˜is one ofā€™ operator for comparisonĀ ā€” perhapsĀ =[

    if ( x =[ 5,6,7 ) ...   or   if ( str =[ "A","B","C" ) ...
    
  42. Avatar for John Bergman
    John Bergman

    Interesting, but I donā€™t really see that much benefit to most of these. I agree with Scott Holodak, my biggest concern about these types of ā€œenhancementsā€ is that they tend to obfuscate the code, and when you are dealing with enterprise applications and their maintenance by experts and novices, I view most of these as an impediment to the end goal; I do, however like #3 and #6 and see some benefit to #7 providing the syntax could be made more readable forĀ beginners.

  43. Avatar for Ricardo Rodrigues

    What about having null checks built into ctors (mixed with auto private field creation)Ā ?

    public class SomeClass(notnull set OtherClass instance) {Ā }

  44. Avatar for Tom Tucker

    Wow #7 would be huge. I thought there wasnā€™t much they could do with C# to entice me to feel like I needed to upgrade. This list makes me want C# 6Ā now.

    I also wish for property fields. Where the variable has class lifetime but can only be accessed inside theĀ property

    public string MyProp {
        string myprop;
        get { return myprop; }
        set { myprop = value; }
    }
    
  45. Avatar for Bobb

    this is going to be total mess if they implement all those syntaxes. especially in large teams where always one or two post graduates who have no clue what they are doing but ā€˜loveā€™ writing cryptic mess.. And the devs who are responsible for pushing out the actual product will waste more time cleaning it.. Much more time than those ā€˜tricksā€™ will save in writingā€¦ #9 is only feature adding something to developmentĀ process.

  46. Avatar for Zach Bray

    The constructor change is a massive improvement over previous versions of C#. Forcing the split between assignment and declaration seemed like a poor design choice. I imagine that fixing it will get rid of many null referenceĀ exceptions.

    It is a shame weā€™ll have to wait so long for C# to catch up with other languages like F# & ScalaĀ though!

    F# is available today and alreadyĀ has:

    • More concise constructor syntax than C#
    • Record types & record expressions (not available in C#)
    • More concise property syntax than C#
    • Language support for tuple types
    • Non-nullable reference types (no need for the ugly '?' operator like C#)
    • Hindley-Milner type inference (far more versatile than C#'s var and proposed constructor inference)

    If anyone reading this would like to learn more about F# (from a C# perspective) I can recommend theseĀ resources:

  47. Avatar for Mike

    After writing and maintaining code for the past 20 years, anything that hides the meaning of code, even if it saves a couple key strokes, is just a bad idea. These are mostly no more valuable than fads and they reduce maintainability. If you want it to be maintainable, code should read like a story. KISSā€¦ the most basic and universal engineeringĀ principle.

  48. Avatar for Joakim

    Why not use the most intuitive syntax for readonly autoĀ properties:

    public int X { get; readonly set; }
    
  49. Avatar for alejandro
    alejandro

    wow! c# slowly moves to scalaā€¦ by the way, your post is clear and interesting!Ā thanks!

  50. Avatar for Mike

    Only number 7 has any chance of making it to C# 6.0. The design team is very, very conservative when it comes to adding features, and most of these are just not worth the effort, especially considering they are rewriting theĀ compiler.

    To predict new C# features, you have to consider what compiler as a service enables. The new compiler will enable you to peek inside the AST, so I suspect more dynamics wrt compiling/inspecting code, not new languageĀ features.

  51. Avatar for Damien

    For 6: Is evaluation deferred until evaluated if you pass a single IEnumerable instead of aĀ params?

    params (certainly for arrays, Iā€™d expect for enumerable also) affects the call site, not the method itselfĀ ā€” once youā€™re inside the code of the method, params doesnā€™t affect anythingĀ ā€” you just have an array or an enumerable. As such, if someone has called your method and passed an array/enumerable directly, you just receive whatever theyā€™ve passed youĀ ā€” the params ā€œmachineryā€ is not involved atĀ all.

    As such, Iā€™d strongly suspect that you get deferredĀ evaluation.

  52. Avatar for Peter Adam
    Peter Adam

    (3) could mean that instead ofĀ the

    MessageBox.Show("Message","Caption",MessageBoxButtons.OK,MessageBoxIcon.Question,MessageBoxDefaultButton.Button1)
    

    could be expressed more like I can do in DelphiĀ now:

    Application.ShowMessage('Message','Caption',MB_OK+MB_ICONQUESTION+MB_DEFBUTTON1)
    

    aka

    MessageBox.Show("Message","Caption",OK,Question,Button1)
    

    It would be the nice comeback of the one line/at a glanceĀ auxiliares.

  53. Avatar for Nikola

    I expected MS to start shifting more towards F#, but itā€™s nice to see C# is still getting plenty ofĀ attention. Those are very nice features. I especially like method expressions and monadic null checking. Features 1ā€“4 I donā€™t like so much, because they seem to me like they will bring confusion into code. I think those are big updates, maybe too big for a mature language such as C#, considering that they donā€™t bring so much value to theĀ table.

  54. Avatar for Adam Ralph

    Nice post! I also thought about writing an opinionated follow up whilst walking to work this morningĀ ;-)

    Iā€™ll put up my follow up post soon, I think my thoughts are largely similar to yoursĀ though.

  55. Avatar for Debiprasad Ghosh
    Debiprasad Ghosh

    Saat nambar ta Ekhani chai (#7 want right now)Ā !

    ā€œMonadic null checkingā€

    var bestValue = points?.FirstOrDefault()?.X ?? -1;
    
  56. Avatar for Spencer Rose

    Some of these are nice, love 7,9 but would love to see some features that change whatā€™s possible rather than cleaningĀ syntax. I would love to be able to use Lambda Expressions as constructor parameters forĀ Attributes

  57. Avatar for Scott Holodak

    Yes please to #6, #7 and #9. Not really excited about any of the other ones. Iā€™d be concerned that #1-#5 would impact readability/maintainability, particularly in teams where you have experts and beginners trying to peacefully coexist in the same codeĀ base.

  58. Avatar for Lyubomyr Shaydariv
    Lyubomyr Shaydariv

    @Damien: thank you for explanation. I donā€™t really know how ā€œparamsā€ is implemented under the hood (I may guess how it works, but not sure), but letā€™s take a start from the idea of ā€œunrollingā€ of what the ā€œparamsā€ is designed for: generally speaking itā€™s designed just to simplify passing more same-typed arguments to variadic methods reducing the number of overloads. So basically all arguments must be evaluated before they are passed to a method in eager manner just like if they were ā€œregularā€ arguments. I think that eager evaluation for method arguments is a must for CLR design, and if lazy evaluation for sequences is necessary, the IEnumerable must be used in the method explicitly, because array (and ā€œparamsā€) item dereferrencingĀ operator assumes that the whole sequence is known, and kept, for non-abstract instance, in memory -- IEnumerable does not have size per se byĀ design.

  59. Avatar for Damien Guard

    @james: While the scoping there would be great for the Try pattern it would render this function useless for DirectX programming where there are a lot of out parameters simply to avoid copying back and forth via theĀ stack.

  60. Avatar for Damien Guard

    @Lyubomyr: With (paramsĀ int someValues) you have two optionsĀ ā€” comma separated parameters and an array. Sometimes we have an array and so we have to pass that. Other times we have an IEnumerable and have to forceĀ evaluation.

    With the new syntax Iā€™d imagine people start switching to the IEnumerable syntax so that you can either comma separate the parameters or pass any enumerable (including array) to be evaluated as required. It should replace the older syntax as time goesĀ on.

  61. Avatar for Lyubomyr Shaydariv
    Lyubomyr Shaydariv

    (1) ā€œprimary constructorsā€ syntax is scary. I donā€™t believe that it can be accepted.Ā Ever.

    (3) is good borrowing the idea of static imports from Java. The code can be much and much cleaner, thatā€™s true. However, Iā€™d like to import particular classes, and other first class members. The ā€œusingā€ keyword is uncontrollable when simply importing whole namespaces. Extension methods introducing is even more uncontrollable andĀ unpredictable.

    (6) Couldnā€™t understand it. Isnā€™t passing IEnumerableĀ enough?

    (9) Unnecessary and, according to James Hart, causesĀ issues.

    (Wrapping Up) I do believe that introducing meta-programming can obtain more efficiency and enhancements at compile time. The given example is about a Decorator design pattern implementation, and a meta-programming template can easily cover this case without enhancing the language itself -- youā€™d enhance the language yourself. Even a simple ā€œforeachā€ statement could be expressed using a template. But itā€™s a differentĀ story.

  62. Avatar for James Hart
    James Hart

    The improvement of inline out variable declaration might be more subtle than just eliminating the need for a prior declarationĀ ā€” it permits the scope of the variable to be reduced to where itĀ belongs:

    Before:

    int i;
    if (int.TryParse(whatever, out i)) { /* do stuff with a valid i */ }
    // now i still exists but is in an 'unspecified' state</pre></code>
    

    After:

    if (int.TryParse(whatever, out int i)) { /* do stuff with a valid i */ }
    // now i is out of scope</pre></code>
    
  63. Avatar for Brandon D

    Liviu I have had something even more robust imo for a long timeā€¦ at maybe.codeplex.com you can doĀ obj.Maybe(x=>x.Prop1.Prop2).

  64. Avatar for Giles

    1, 4. 5 for extraĀ readability.

    pattern matching would beĀ great

  65. Avatar for liviu

    Safe navigation is a killer, now i use following to simulateĀ it:

    obj.Safe(x=>x.Prop1).Safe(y=>y.Prop2)
    

    Safe is R Safe(FuncĀ propaccess)ā€¦

    What bothers me in these examples, is that the new features are just some cosmetic stuff, easy to implement by anĀ intern, when having a good parser likeĀ Roslynā€¦

    Why not syntactic macros, or again: string interpolation like many new and old languages have implemented forĀ ages? Why is C# soĀ conservative?

  66. Avatar for Enrique
    Enrique

    I canā€™t wait for #7. Iā€™d actually be willing to kill for it rightĀ now.

  67. Avatar for vincent
    vincent

    This is NOT monadic null checking Monadic null checking would be using an Option or Maybe class and using LINQ extension method (specifically SelectMany) for stacking checks suchĀ as

    var opt =
        from o1 in maybeNull
        from o2 in o1 ///which also might be null
        select new Test() { a = 01.Text, b = o2.Text };
    

    Make sense?

  68. Avatar for David

    Imitation being the sincerest form or flattery; F# should be very flattered! Still, looks a nice set ofĀ improvements.

  69. Avatar for Channs

    For (1) Primary Constructors, I prefer a syntax which allows me to prefix the private instance variables with an underscore ( _x and _y ). This naming convention makes the code more readable, since one can easily distinguish between private instance variables ( _x and _y ) and method local variables ( say m and nĀ ).

  70. Avatar for Boris Letocha
    Boris Letocha

    I hope you will be also able toĀ write:

    dict.TryGet("123", out var x)
    

    It is one of places there you have to declare type and cannotĀ use var.

  71. Avatar for Nicolas
    Nicolas

    Yeah! Letā€™s add more keywords doing nothing new in new ways and call that a new versionĀ !!

    Seriously, I feel bad for CSharpers. It is really time they jump on the Fsharp wagon which is all thatā€™s left to be cool on theĀ CLR.

  72. Avatar for Josh Jeppson

    I feel like Iā€™ve been waiting for Monadic null checking (7) all my life. Primary Constructors (1) is a fantastic idea but I am not a fan of the given syntax. I like your rewrite. My first thought was to use the ā€˜thisā€™ keyword, but ā€˜setā€™ allows it to be intuitive in static constructors as well. Iā€™m not sure I like the idea of auto-creating private fields/properties if they donā€™t exist. That seems like it could easily cause confusion with anyone not familiar with the languageĀ feature.

  73. Avatar for Liviu

    I would love to see more hardcore features likeĀ : string interpolation dynamic enhancements and not least: Lambda Expressions to supportĀ statementsā€¦

  74. Avatar for Keith Dahlby

    Whatā€™s interesting about inline out declarations this is that a series of statements is now replaced by an expression, so you could do something likeĀ this:

    s => int.TryParse(s, out int x) ? x : default(int?);
    
  75. Avatar for Damien Guard

    Thanks Jesper that makes a lot more sense, I was sure I was wrong. I will update theĀ post.

  76. Avatar for Jesper

    4/5: ā€œExpressionā€ in this context does not mean involving expression tree types at all, just expressions that are not standalone statements in brackets. Like how ā€œ1 + 2ā€³ in ā€œ() => 1 +2;ā€ is not ā€œ() => { return 1+ 2;Ā }".

    So:

    public double Distance => Sqrt((X * X) + (Y * Y));
    

    as a shorter way ofĀ writing

    public double Distance {Ā get { return Sqrt((X * X) + (Y * Y)); } }
    
  77. Avatar for Blake Niemyjski

    Itā€™s going to be interesting how these play out. Iā€™m not sure I like the syntax for #1 orĀ #2