Tuesday 22 April 2014

New features for c# 6 part 2

This is part 2 of the new features for c# 6, see part 1 here. All these features are already done for c# 6, where the part 1 is planned features.

Primary constructors

Primary constructors a shorter way to write a constructor that automatically assigns to private instance variables. The constructor is defined with the class itself as class Point(int x, int y) { … }


Auto-property initializers / Getter-only auto-properties

Another shorthand for properties that only retrieve/assign the value to a private member. Now you can do this public int X { get; set; } = x; You can also use an getter-only auto-property, which is perfect for immutable classes! public int Y { get; } = y; 


Using static members

In your using statements you can have static members to have all methods easily accessable in that class. As so using System.Console; … Write(4);


Dictionary initializer

Dictionary initializer is another short hand. new JObject { ["x"] = 3, ["y"] = 7 } would be the same as jsobj = new JSObject(); jsobj["x"] = 3; jsobj["y"] = 7;


Indexed member initializer / indexed member access

This is quite basic but really awesome. Lets take the example from before new JObject { ["x"] = 3, ["y"] = 7 }. Doing this with indexed member initializer would be new JObject { $x = 3, $y = 7 }. So object["x"] is the same as object.$x which can be used in the initializer or when accessing normally.


Declaration expressions

With declaration expressions you can declare a variable when calling a method with the out parameter. For example when parsing an int using the TryParse method you can declare the variable to out, when calling the method as such int.TryParse(s, out var x);


Await in catch/finally / Exception filters

You can now use await in catch/finally try … catch { await … } finally { await … } and as a new thing you can filter your exceptions with an if clause so it will only be caught if the terms are matched catch(E e) if (e.Count > 5) { … }

No comments:

Post a Comment