Hacker News new | past | comments | ask | show | jobs | submit login
What's New in C# 6.0 [video] (msdn.com)
227 points by chton on Nov 14, 2014 | hide | past | favorite | 142 comments



You can also view a summary of the video/features as a presentation: https://view.officeapps.live.com/op/view.aspx?src=http%3a%2f...


Can't get past slide 4 (blue spinning ball on the cursor, yay Office Live).

Anybody have a pdf version?



works perfectly fine on Chrome, IE, and Firefox.


yeah that happened to me on Chrome. Try IE.


Thanks. Looks pretty awesome!


It's also much the same content as: http://msdn.microsoft.com/en-us/magazine/dn802602.aspx


Interestingly, if you'd like to check out how some of these features were implemented, you totally can. Roslyn is open-source (http://roslyn.codeplex.com/).

That being said, I hope that all the open-sourcing is going to make it available where I really want to use it - Unity, for instance. (Disclaimer: I'm an open source dev @ Microsoft)


I was hoping Unity would start loosing some market due to outdated Mono. I guess we are in for another github-like "monopoly".


Nah, it won't have a monopoly. UE4 is a big deal for a lot of reasons, particularly its graphical quality. It's not the friendliest for indie devs at the moment, but it's been evolving and improving very rapidly.

And we'll see how long it takes Unity to actually support the current C#. My guess would be a couple years, since Unity 5 isn't even out yet, and there's usually 18 months between major releases.


Nothing not to love -- a whole bunch of syntax sugar that makes code cleaner without messing around with core concepts that breaks code conceptually. It's also great to see how quickly good ideas permeate the language landscape today versus ten years ago (or maybe it's just good ideas finally permeating the landscape all at once).


From what I understand, this has been on the list for awhile, they are just working through it in each version. None of the ideas are very new at all, and could have been on the list quite awhile ago.


It is really nice to see good ideas percolate in from other places. I like the focus on making syntax cleaner and less boilerplate without being overly terse.


I'm going to take some hits for that but... with .NET being open source (never liked Mono..) and all..

I'm tempted to use C# in the future again. Using it on Windows has always been good - and now that it compiles to native code too and that the libs are open....


Why would you take hits for doing something in a language you like?


I thought that native compilation was only for "Windows Store" apps. Do they now have that available for regular Windows desktop apps too (or more importantly, server-side Linux apps)?


I haven't played with it much, but it says in the FAQ[1] :

"Will Server/Desktop apps benefit from .NET Native and/or the Compiler in the Cloud?

Desktop apps are a very important part of our strategy. Initially, we are focusing on Windows Store apps with .NET Native. In the longer term we will continue to improve native compilation for all .NET applications."

[1] http://msdn.microsoft.com/en-US/vstudio/dn642499.aspx


I'd love to be able to write drivers in c#.


Xamarin for iOS compiles to native as far as I am aware.


Native code will be supported across the board for Windows 10 devices,

http://www.hanselman.com/blog/AnnouncingNET2015NETAsOpenSour...

Unless Windows Desktop is meant as store applications.


Still hoping they add the !(non-nullable) operator.

I know its hard http://blog.coverity.com/2013/11/20/c-non-nullable-reference...

But dang I would appreciate it. So much code is cluttered with null checks that increases the robustness of the code at the cost of correctness, readability, and poorly defined behavior.


Aren't you just shifting the problem rather than solving it?

For example, let's say I am calling a function which returns an object:

       var myStuff = new GiveMeStuff().GenerateStuff(1337);     
The return of this value can be valid "stuff," an exception, or null. If we remove null as an option, what happens when internally an exception is thrown within GenerateStuff()? Does it re-throw that exception? Or do we now need a property within stuff like (bool)myStuff.validStuff?

Null is a very useful way of communicating something failed. It is useful firstly because it is a "cheap" comparison and secondly because it saves us from having to place try{}catch(){} blocks around all of the things.

So my question is: without null how are we communicating failure? More exceptions? Or more clutter within our objects.


Null values don't go away, it's just that reference types aren't by default nullable. Your function can still return null (if you really want it to) as long as that is indicated by the return type. What you can't do is directly assign the possibly null return value of your function to a non-nullable reference.


Languages like Haskell, Swift, and Rust use an optional type[0] for nullable things. Most things don't need to be nullable, and by being explicit about it in your type you convey your intent - ie. 'this thing might fail, and you must handle it if it does'.

- [0]: http://en.wikipedia.org/wiki/Option_type



In my limited C# experience I found `int?` to be really nice, and an operator to non-null it sounds even nicer.

I wonder if there is any chance of Rust getting an abbreviation like `?` so you can write `int?` instead of `Option<int>`. I'm just starting to explore the language, but it seems like a lovely addition.


Rust is trying to reduce the amount of magic in the libraries as much as possible. This means that whatever the language/standard library authors have available to them, third party library authors should also have access to. `T?` would probably run against that, given the previous removal of `@T`, `~T`, `~T`, and `~str` in favor of `Gc<T>`, `Box<T>`, `Vec<T>`, and `String`.


Rust's syntax has actually been getting more wordy and less variable-y. At least, that's what happened when the changed around Box and some other syntax-sugar'd variables.

I wouldn't expect Rust to go back to shorthand after leaving it.


While all of the changes look nice in terms of writing less code, they are the kind of syntactic sugar I learned to hate in CoffeeScript. Mostly because the code was so much denser and harder to read. Especially when reading other people's code.

As I write more and more code, the more I want simplicity and ease of understanding over typing a few less characters or having more elegant code.


I think what's important is that they are making good choices, such as immutability, take fewer lines of code. This pulls the default developer in the direction of writing immutable by default, which I think is great change.


As I write more and more code, the more I want simplicity

I had a 24 year old developer report to me that apparently thought his bonuses were tied to how many operations he did on a single line of code.

He consistently wrote unbelievably complex lambda expressions with multiple conditional operators that would make a single line take up at least 1.5 screenfulls in Visual Studio on a 1920x1080 resolution monitor. These lines were impossible to debug and had to be inevitably broken up.

For a while I thought he was following the conventions laid forth in:

https://www.thc.org/root/phun/unmaintain.html

...but he really seemed to be genuinely thinking he was accomplishing something good by doing this.

I'm with you though. I'll take simplicity.


Ha! "Exploit Compiler Name Length Limits"

I worked for many years on a FoxPro application with a 10-character limit. The first version of the program was written under a two character limit. This never bothered my boss, who was a terrible typist and always used short names anyway. But I at some point took up the practice of descriptive names, on top of the Hungarian notation we'd adopted for sanity. So I was exceeding the limit all over the place.

Ten years later, guess who had to convert the program to VFP, which has no variable name limit. And no compile-time checks on variables, even when they are declared. Glad that year's over.


Well it depends how you do it. There's certainly some mileage in doing it like that properly:

http://blogs.msdn.com/b/lukeh/archive/2007/10/01/taking-linq...


Over the board or just expressive? http://programmers.stackexchange.com/a/261893


That's fascinating, because Steve Yegge suggests that density tolerance is a factor of skill. http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.htm...


On the other hand, Steve Yegge and people like him (ESR for one) always suggest that whetever they like is "a factor of skill".


Isn't that what the APL/J/K people keeps saying? I guess sometimes it makes sense to optimize for hunting deer rather than optimizing for special forces ops (Even if spec. ops. probably are fierce deer hunters...).


I'm with you, both for your reasons and for another: it makes code harder to teach. "Oh, you'll see this. And this. And this . . . There's this, but no writes it that way. This is idiomatic."

There's some of this in all languages, of course, but "this bit of sugar will make the code cleaner and easier to read" assumes that everyone will adopt a new set of idioms wholesale (which they usually don't).


I have spent a large portion of my career teaching new developers. I think C# is a pretty terrible first language already. The sugar here and there is nothing compared to the massive mental burden of OO, inheritance, compilation, DLLs, Visual Studio, etc etc etc.

Scheme, via SICP, is much easier to get started with, and one can learn the basics with that quickly (including getting much more comfortable with the sequence abstractions -called LINQ in .NET- than even the average .NET developer).

All these reasons are also why I greatly prefer F#. If you stay away from much of the OO system, F# is much simpler to teach in my experience. At my company right now another team is putting together an F# training program intended to teach our QA automation.


The vast majority of these changes are very understandable. The only one that is complex is the ? operator, which compresses only code that is very uninteresting and harder to read.

Comparatively the string trick, read-only properties and lambda syntax for simple methods seem very easy to digest.


>>> the more I want simplicity and ease of understanding over typing a few less characters

True, coming from Java where you have to type a lot to get a simple thing done I seem to be gravitating towards languages which have clean, simple syntax that allows you to actually think about the problem. I've been playing with python and scheme, I'll have a go with C# soon, now its been open-sourced.


Go would fit that definition quite nicely as well. It may be worth adding to your list of things to check out.


Better do it before checking out C#....


Thanks exch and pjmlp, I will check out Go before C#


I was being sarcastic, because you will be disappointed if you learn C# first.


>While all of the changes look nice in terms of writing less code, they are the kind of syntactic sugar I learned to hate in CoffeeScript. Mostly because the code was so much denser and harder to read. Especially when reading other people's code.

Syntactic sugar can be that, but not THIS syntactic sugar they propose here.

Here it makes the code easier to read and the intent more clear.


There is an optimal level of complexity per line of code that you should try to keep constant throughout your project. It's like a meal, I'd rather have something light like a salad and some soup over eating a 1 lb bar of chocolate for dinner.

Reading code should be like reading a nice book.


Manager: "Why isn't the project done yet? Why are you still coding?"

macromaniac: "Patience, I'm still working on salad..."


Most of the features make the language more consistent and reduce syntactic noise, making it easier to read. The only feature that puts additional mental burden is the elvis operator.


Don't even try F# then :). Syntax is terse, but so academically alien.


Still no first-class tuple support? Argh! All want is:

  var first, last = parseName(fullName);
Instead of:

  String last;
  var first = parseName(fullName, out last);


Totally agree on the need for tuple syntax (and pattern matching to make it really useful):

    return Tuple.Create(foo,bar);
Should be:

    return (foo,bar);
The worst part is using the Item1..ItemN properties. One way I've gotten around it is to create a Tuple extension method called Apply [1]. I allows you to do this:

    ParseName(fullName).Apply((first, last) => ... )
That allows for giving names to the tuple ItemX fields and uses them 'in scope'.

At least with C#6 we can now open static classes like namespaces and do something this:

    using Language.Helpers [2]

    ...

    return tuple(x,y);
Which already makes it start to feel like it's part of the language.

[1] https://gist.github.com/louthy/f4cee2524d0d049b4378

[2] https://gist.github.com/louthy/dc06868c446ed76f0d7a


Apply creates new scope, which is often undesirable. Consider the "Declaration expressions" feature in C# 6:

  ParseName(fullName).Unpack(out string first, out string last);
However, this makes for essentially left-to-right assignment, which is contrary to the usual order. So this creates discontinuity when moving from one return value to two return values.


My personal opinion is 'out' is a total abomination. I will do everything I can to avoid using it. I prefer expression based programming where there's a balance between the two sides of an operator. Declaring named values on the RHS is just horrible (again, IMHO). The only reason for it to exist is because C# hasn't got proper tuple support.

By the way, creating a new variable half-way down a method is also creating a new scope (the variable isn't in scope above the declaration, and it is in scope below it, until the end of the method).

For example:

    public int GetSurnameLength()
    {
        string fullName = ReadFullNameFromDb();
        Tuple<string,string> result = ParseName(fullName);
        return result.Item2.Length;
    }  
Has the same effect as:

    public int GetSurnameLength()
    {
        string fullName = ReadFullNameFromDb();
        return ParseName(fullName).Apply( (first,last) => last.Length );
    }  

The only real downside to the Apply method is the syntax clutter from the closure. But there's no real issue with scope as far as I can tell (because the rest of the method can be within the closure if necessary). This is very similar to how 'let' works in F#.


Agree with the complaint but not the workaround; there is Tuple<string, string>, after all, so maybe something like this?

   Tuple<string, string> fullName = ParseName(fullName);
   var firstName = fullName.Item1;
   var lastName = fullName.Item2;


i think it's because they rather have you pass in fullName string and get back a typed Name object instead.

that second example is always a bad choice and i would never but i do agree a little tuple support would be nice as a trap door kinda feature to avoid code like this


Having to create a class for everything is a chore, it doubles the amount of named things in the codebase. It also creates an undue discontinuity when moving from one returned value to two returned values during the process of codebase evolution.

Either first-class tuples or anonymous classes as return types would reduce this cognitive overhead.


Seems like a small change but that nameof(argument) method for ArgumentXExceptions is incredibly handy.


And also for INotifyPropertyChanged! (Although CallerMemberName helped that some in C#5.)


Still wish they would implement something better for INotifyPropertyChanged like key-value observing in obj-c or object.observe proposed for js. Basically automatic property changed events. At least this removes the magic strings in the boiler plate.


I've really wanted to have some sort of property token similar to how we can use method groups as tokens for event subscriptions and delegate creation.

I've also wanted a system similar to dependency properties in WPF that was a little lighter weight. DPs do pretty much everything i could ask for from change notification to binding to pluggable validation, I just wish they we not so tied into the WPF code so i could apply them to my data layer.


I really really want property change notifications on auto-properties. Having to compare the incoming value against an explicit backing field is the cause of most of my boilerplate code when using WPF.


I wrote a framework that wrapped dependency properties to accomplish things like this once:

http://bling.codeplex.com

But my feeling is that it was kind of hopeless to do in C#: it is just so different from the language semantics. Something like FRP (real FRP, not Rx) or managed time [1] works much better, IMHO, but requires drastic language changes.

JavaFX Script (F3) also included data binding straight into the language, and is probably an idea of how to do it for C#.

[1] http://research.microsoft.com/en-us/people/smcdirm/managedti...


Gosu has a feature called feature literals [1] giving you access to the reflection information so you can write something like Customer#Address.PropertyName or Customer#Address.PropertyType but I am not sure how much of that is evaluated at compile time.

[1] http://devblog.guidewire.com/2011/03/03/feature-literals/


F# one ups this by letting you implicitly pass arguments as quotations.


Being able to use await in catch and finally must have been incredibly hard to implement for them. Especially in the finally part.

I mean - I'm saying this as somebody who hasn't done a lot of C# or .NET work in the last few years, but think about what you would have to do if you had to implement this in a safe and bug-free way.


Given that the 'vanilla' async-await isn't always safe/bug-free, I can't imagine that the harder version will be.


The null-conditional operators and string interpolation are really cool.

I don't use C# anymore (job change, not out of dislike), but I was always really happy working in it. I'm still not a huge fan of Windows, but C# is a wonderful language.


I wonder how string interpolation interacts with translation though? I thought the whole idea of the numbered placeholders was so that you could translate the string and rearrange them for different languages. Now do your translators have to be careful not to break your code if they're editing it as part of the string?


Even if an application gets localised, it may do less formatting of localised messages than of non localised ones (think (debug) logging, textual protocol formatting, exception messages and the like)

I also expect that a large fraction of applications never gets localised (in-house tools, scientific software, etc).

In total, I think there are orders of magnitude more lines of message formatting code that do not get translated and likely never will be translated.

It appears modern language designers think it worthwhile to make life for that use case a bit easier.

(it is not that the code gets much shorter, but more that, for true translation, you have to move the format string into a resource, and load it from your code)


That's a good point. I imagine it will require consideration by the developer/architect of how to handle internationalization. It may be that you don't want to use string-interpolation for any strings that require translation.


.NET has a higher level built-in mechanism for dealing with translated content (Resource files). I don't think this new language feature is intended to replace that.



> New feature: Go To Definition

Oh those poor, poor souls who have had to work in C#'s shadow.


Not knowing anything about VB these days, this video almost looks like satire :P


I'm sorry for my coworkers and whoever else around me - I will now shout "NEW FEATURE" constantly.


Using static classes as namespaces addresses something I was just complaining about a week ago. Let's take it a step further! Just let us put bare functions in namespaces without the dance of the static class.


>Let's take it a step further! Just let us put bare functions in namespaces without the dance of the static class.

No. C# is an object-oriented language. It doesn't have functions, it has methods. Methods are always attached to a class. Even anonymous methods (lambdas) are compiled to be a method on a class (like c__DisplayClass1).

"Bare" or "global" functions have no place in C#.


If you think that way, then C# left you behind a long time ago. Because if functions had no place in C#, then there would be no static classes in the first place. The static class is nothing more papering over object oriented bureaucracy that "everything is an object" to provide functions. And using a static class as a namespace furthers that.

I get that the CLR expects a certain way of implementing things. But your own example of Lambdas are an excellent example of how we can use syntax to overcome bureaucracy in the runtime, or else we would be stuck in Java land with anonymous classes implementing interfaces.

Ultimately, it's all sugar. If a static method of a static class can be made to look like a function in calling code, then it makes sense to make it look like a function in the definition.


> The static class is nothing more papering over object oriented bureaucracy that "everything is an object" to provide functions.

Classes (in typical static, class-based "OO" languages like C++/Java/C#) aren't objects, and static classes are classes that don't even relate to objects the way that "normal" classes do. Static classes as containers for functions aren't papering over object-oriented bureaucracy that "everything is an object", they are papering over class-oriented bureaucracy that "everything is connected to a class".

(This is a general agreement with your basic point, though.)


F# module == C# static class. What is the problem?


static classes and namespaces seem to have a lot of overlap now. Static partial classes can almost completely replace namespaces now.


So F# modules is an unnecessary concept too?


Judging from at least the implementing code, "using static classes" in C# and "opening modules" F# are the same operations.

But we're talking about C# here, not F#. F# is a fine language, but not pertinent to any project I'm working on right now.


I think they missed a trick if the goal was to reduce boilerplate; which I'm all for, I'm very much moving away from C# to F# for this reason (and a few others).

Why this:

    public int X { get; }
    public int Y { get; } = 5;
And not this:

    public int X get;
    public int Y get = 5;
The braces serve absolutely no purpose anymore, the semi-colon doesn't serve as a separator between statements. So why leave them?


I can comprehend braces faster than I can read the word "get". Sometimes structural code is useful as a navigation and comprehension aid. I've been doing a lot of python lately and I am much slower at scanning a file to find a piece of code or understand its structure precisely because everything is just words. This recent trend towards naive minimalism in language design is awful.


public int X { get; } is more consistent with how properties are declared. Consistency is important.

If you care about clean code, here's an even better way public readonly int X; They are not exactly the same but they are equivalent in most cases. In exotic cases where you're required to use auto-getters, adding the brackets wouldn't hurt.


> public int X { get; } is more consistent with how properties are declared. Consistency is important.

As mentioned in my other reply. If that were the case, why have they just changed the method declaration syntax? It's inconsistent and therefore unacceptable right? If everything has to be consistent we wouldn't have LINQ, lambdas, generics, etc.

The braces are for scope in C# and all C derivative languages. There is no scope being created here and no requirement for scope. Also there are other places in C# where the scoping braces can be dropped [when there's only a single statement within]:

    if(foo == 1)
    {
       bar();
    }
Can be written:

    if(foo == 1)
       bar();
So I don't see the inconsistency at all if they were to drop the braces.

> If you care about clean code, here's an even better way public readonly int X

That's what I use. Cue the next round of discussion about fields and properties...


>As mentioned in my other reply. If that were the case, why have they just changed the method declaration syntax?

They did change the property declaration syntax too.

    public int X => 5;
is the same as

    public int X { get { return 5; } }
This is exactly the same change they made to the method declaration syntax, so I'm not sure what you're complaining about.

Of course it isn't identical to public int X { get; } because the latter is assignable in the constructor. But comparing _that_ to methods is apples to oranges since methods aren't assignable.


I think you're quoting me out of context here. I am debating the consistency angle. My argument is that if there is such a drive for consistency (and therefore that's a good reason to keep the braces) then the method syntax wouldn't have changed to drop the braces. So I feel that argument is moot when discussing the reason for keeping the (what I believe to be) ugly syntax of X { get; } = 5;

Your example of the computed properties is not the same. I like the computed properties syntax, but unless the properties can be computed from the constructor parameters then you will still need to either use the ugly property syntax, or readonly fields to get the same immutable guarantees.

Personally I am fine with using readonly fields, I was only commenting on how the C# team have (in my opinion) missed the opportunity to get rid of some of the unnecessary clutter. I know however many people don't like using readonly fields for various reasons: serialisation, data-binding, interface declarations, etc.


Because people like braces (they provide structure) and there is a risk to break backward compatibility. Granted the whole ;} = 5; syntax is not great ....


That must be why they removed the need for braces with 'lambda' methods right?

It just seems so pointless and ugly, no one is going to write them like this (well, seems unlikely anyway):

    public int X 
    {
        get;
    } = 5;
So they're no longer providing a scope/block structure. How would it break backward compatibility? I'm not suggesting they remove the scoping for properties, it's clearly needed for {get;set;}, but as far as I can tell I can't think of any existing property-name suffix keyword in the C# grammar, so it seems it wouldn't be too hard to get it to work.

The only reason I can think of to not do it is to reserve the option of post property-name keywords for future features.

I've been using public readonly fields instead for a number of years now because of the constant boilerplate. I doubt I'll change to use these auto-properties for the same reasons.


For the second one you can write this:

    public int Y => 5;


It isn't the same. With immutable properties the constructor can change the value of Y based on its own decision logic. So 5 is just a default and the constructor may change it. That allows for multiple constructors, some that set the value some that don't.

If the value is always going to be 5, then use a const.


I'm a tiny bit disappointed with the inclusion of exception filters, but I suppose it is pragmatic feature.

I'm fond of a pattern where error codes can be implicitly converted to Exceptions[1].

It's often argued that exceptions are for things that your program cannot handle and error codes are for things that it can. But, in my experience, whether or not a bad condition is an error or an exception depends upon the layer in which the code lives.

Also, a side benefit of this scheme is that most of the exceptions show up in the class browser, or can be explored through reflection.

[1]https://gist.github.com/noblethrasher/ba37ed6176ebeb679dd2 -- In my example, the error code is an integer, but it could be another class that holds more information about the operation.


I've never seen the arguments for error codes vs exception. Care to explain briefly or link me some information?


Here's the first essay I remember on the subject: http://www.joelonsoftware.com/items/2003/10/13.html


These are very nice changes. Especially the ability to write a quick lambda for named functions (or functions which are needed often).

The elvis operator is useful to. Makes me think sticking to F# will cause fewer classes of bugs that can happen in C# (the onChanged example is quite interesting).


i love the new "?." similar to coffeescript. definitely make our lives easier.


I knew I'd seen that somewhere before, good call. There's a lot of things in coffeescript I'd love to see in other languages.


To be fair, the first time I saw this was in Groovy, almost ten years ago.


What is this called? It's impossible to google for


The "Safe Navigation Operator" - http://groovy.codehaus.org/Operators


Informally the "Elvis operator".



So these lines are now equivalent:

   public override string ToString() { return String.Format("({0}, {1})", X, Y); }
   public override string ToString() => "(\{X}, \{Y})"
Could it go even further? This isn't paper after all, on screen why shouldn't it look like;

   public override string ToString() => "(X, Y)"
where the X and Y are either slight italics or underlined or colored to indicate they mean X and Y the variable not X and Y the letters. The IDE would let you just toggle the state between 'variable' and 'literal' with the keyboard.

We also get better array initializers:

  public JObject ToJson() {
    var r = new JObject();
    r["x"] = X;
    r["y"] = Y;
    return r;  
  }
becomes:

  public JObject ToJson() => return new JObject() { ["x"] = X, ["y"] = Y };
That's cool! Next comes the null-conditional operators:

  public static Point FromJson(JObject json)
  {
     if (json != null &&
         json["x"] != null &&
         json["x"].Type == JTokenType.Integer &&
         json["y"] != null &&
         json["y"].Type == JTokenType.Integer)
     {
         return new Point((int)json["x"], (int)json["y"]);
     }
     return null;
  }
Becomes...

  public static Point FromJson(JObject json)
  {
     if (json?["x"]?.Type == JTokenType.Integer &&
         json?["y"]?.Type == JTokenType.Integer)
     {
         return new Point((int)json["x"], (int)json["y"]);
     }
     return null;
  }
The check against JTokenType.Integer is just to avoid a casting exception. The null checks are just to avoid null exceptions. I wonder if the compiler could ever handle something like 'this if you can, else null', without actually having any exceptions getting throw and caught underneath:

  public static Point FromJson(JObject json) => 
      return new Point((int)json["x"], (int)json["y"]) ?: null;


>where the X and Y are either slight italics or underlined or colored to indicate they mean X and Y the variable not X and Y the letters. The IDE would let you just toggle the state between 'variable' and 'literal' with the keyboard.

A big nope from me.

Nicer visual representation is OK.

Changing syntax based on visual attributes it's not.


[Edit: this perhaps should have been "Changing semantics based on visual attributes is not"].


IntelliJ has code folding that can display things using a less verbose syntax. For example, folding of closures (pre-Java 8):

http://blog.jetbrains.com/idea/2009/03/closure-folding-in-in...


where the X and Y are either slight italics or underlined or colored

You might find this interesting if you're thinking along those lines: http://joshondesign.com/2014/08/22/typopl


>where the X and Y are either slight italics or underlined or colored to indicate they mean X and Y the variable not X and Y the letters

So what happens if you open the file in a different editor?


I guess it could show up with the \{X} escape notation in Notepad. But in theory almost no one would even notice that, the "natural form" would be to eliminate excessive escaping and just show what the string will actually be.


Why are we letting 50 year old technology constrain us? Why should we ever expect to edit code in a bare bones text editor? I'm not saying I like this particular idea but we shouldn't be held back by our technological history


It's funny that of all those, i'm most excited about nameof


Because primary constructor was slashed to make a true record type, my new favorite feature is the nameof operator, it is very useful with IPropertyChanged, when you have to use the name of a property to raise a change, it was not type safe if you refactored the name of the property, a workaround used Expression capturing using RaisePropertyChange(p => p.MyProperty) which is very slow (or a CallerMemberName attribute in C# 5 but can be abused), nameof is more elegant.

I also love the ?. operator.


They need to add these:

https://github.com/MiniProfiler/dotnet/blob/master/StackExch...

They're extremely useful and intuitive string helper methods. Truncate(), IsNullOrWhiteSpace(), etc are things I use daily. And while you can type string.IsNullOrWhiteSpace(string) that is annoying and counter-intuitive.


IsNullOrWhiteSpace() was added in dot net 4: http://msdn.microsoft.com/en-us/library/system.string.isnull...

I agree that Truncate would be a nice one to include in the core.


> IsNullOrWhiteSpace() was added in dot net 4:

Look at what the helper actually does. I already addressed this in my comment.

     string hello = magic();    
     if(hello.IsNullOrWhiteSpace()) 
     { ... }
Is significantly more intuitive than:

     string hello = magic(); 
     if(string.IsNullOrWhiteSpace(hello))
     { ... }
Plus it is consistent with things like Contains("XYZ") (e.g. hello.Contains("something")).

Truncate is useful just because Substring() throws a bunch of dumb exceptions. It is mostly a workaround for Substring's poor design.


That defeats half the purpose though, because if the string is null, you won't be able to call the method without throwing an exception. Or is that not the case for extension methods?


Extension methods are rewritten by the compiler to a normal static method call with the subject as their first argument (that's how they're defined, anyway). And since you can legitimately pass null to those methods there will be no NRE by default.


Calling IsNullOrWhiteSpace on an instance looks even more counter-intuitive to me, though – it wouldn't work on null if it were a real instance method.


It is consistent with how other .Net libraries work (particularly the string ones). It also works fine on null as long as the type of null is string.


It works because it's an extension method, but aren't extension methods supposed to make things nice and consistent by making it look as if you're calling an instance method?

Since this would be completely broken if it were an instance method, the reader might be surprised at first until they realize it's an extension method. So all I'm saying is that it's no less "counter-intuitive" than the normal string.IsNullOrWhiteSpace.


Indeed, the fact that extension methods happen to work with `this == null` is more of a bonus feature than something that should be deliberately used.


I did a talk a few months back going over the changes up until today, and what is coming in C# 6, this was before they decided to drop primary constructors.

https://www.youtube.com/watch?v=BA3sL783_Co


It all looks really promising. Love it.

I'm a little worried about "nameof" in the hand of amateur programmers though. Efficiency aside (because it's not efficient), code readability might take a hit.


He explains that this is for refactoring.

As others have said, I'd therefor expect this to be a purely compile-time feature that just inserts the name of the reference within. The whole reason for this keyword seems to be that you have no string ("foo") but a reference/name instead (foo). Which can be picked up easily by tools.


It's syntactic sugar, semantically equivalent:

nameof(foo) <=> "foo"

Efficiency doesn't change


It shouldn't have any efficiency implications. I have to imagine that it is interpreted at compile time, similar to the var keyword.


Good for reflection and renames. ReSharper helps but I don't want to rely on it.


I love the new read-only auto properties. 90% of the objects I write are immutable and it's a pain to declare all those private readonly backing fields just to return them in getters.


Agreed, I hardly ever used auto-implemented properties for that reason. But, Is the backing field for a read-only auto-property still readonly (i.e. only assignable from within a constructor body)?


Yes, the backing field is readonly.


Why don't you use public readonly fields?


Interfaces and overriding usually.


Lots of little things but they're pretty handy. I wish I still wrote in C#; perhaps that day will come when they start distributing the .Net runtime on Linux / Mac OS X.


Crazy, that will never happen :)



await in catch and finally is going to be great! I'm an amateur c# programmer, but I hated having to set flags that get called later to do async methods with try/catch.


Good to see immutability being given some attention. Elvis operators though, I think they make code shorter rather than easier to understand


More fun for the juniors who have just come to terms with the ternary operator.


It has only been like 50 years since it was introduced. The juniors are coming to terms with retirement now.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: