
What's New in C# 6.0 [video] - chton
http://channel9.msdn.com/Events/Visual-Studio/Connect-event-2014/116
======
iaskwhy
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...](https://view.officeapps.live.com/op/view.aspx?src=http%3a%2f%2ffiles.channel9.msdn.com%2fthumbnail%2f6fcbe7ba-1cf1-4332-a9e3-ad559fe907c1.pptx)

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

Anybody have a pdf version?

~~~
ComputerGuru
Here you go: [http://cl.ly/0C25161f2T1q](http://cl.ly/0C25161f2T1q)

------
felixrieseberg
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/](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)

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

~~~
TillE
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.

------
Tloewald
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).

~~~
seanmcdirmid
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.

------
zobzu
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....

~~~
StevePerkins
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)?

~~~
pionar
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](http://msdn.microsoft.com/en-
US/vstudio/dn642499.aspx)

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

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

I know its hard [http://blog.coverity.com/2013/11/20/c-non-nullable-
reference...](http://blog.coverity.com/2013/11/20/c-non-nullable-reference-
types/#.VGY_5fnF-QA)

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.

~~~
Someone1234
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.

~~~
bmm6o
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.

------
wbond
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.

~~~
300bps
_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](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.

~~~
gavinpc
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.

------
DenisM
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);

~~~
louthy
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](https://gist.github.com/louthy/f4cee2524d0d049b4378)

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

~~~
DenisM
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.

~~~
louthy
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#.

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

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

~~~
SigmundA
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.

~~~
algorithmsRcool
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.

------
pilif
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.

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

------
hvs
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.

~~~
chrisseaton
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?

~~~
Someone
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)

------
IdleChris
What's new in VB 14 (video): [http://channel9.msdn.com/Events/Visual-
Studio/Connect-event-...](http://channel9.msdn.com/Events/Visual-
Studio/Connect-event-2014/113)

~~~
edgyswingset
> New feature: Go To Definition

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

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

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

------
moron4hire
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.

~~~
pionar
>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#.

~~~
moron4hire
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.

~~~
dragonwriter
> 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.)

------
louthy
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?

~~~
zer0nes
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.

~~~
louthy
> 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...

~~~
Arnavion
>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.

~~~
louthy
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.

------
noblethrasher
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](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.

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

~~~
noblethrasher
Here's the first essay I remember on the subject:
[http://www.joelonsoftware.com/items/2003/10/13.html](http://www.joelonsoftware.com/items/2003/10/13.html)

------
architgupta
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).

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

~~~
EStudley
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.

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

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

~~~
grokys
Informally the "Elvis operator".

~~~
zak_mc_kracken
Correct: [http://groovy.codehaus.org/Operators#Operators-
ElvisOperator](http://groovy.codehaus.org/Operators#Operators-
ElvisOperator)(?:)

------
zaroth
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;

~~~
towelguy
>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?

~~~
zaroth
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.

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

------
hokkos
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.

------
Someone1234
They need to add these:

[https://github.com/MiniProfiler/dotnet/blob/master/StackExch...](https://github.com/MiniProfiler/dotnet/blob/master/StackExchange.Profiling/Helpers/ExtensionMethods.cs)

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.

~~~
ColinDabritz
IsNullOrWhiteSpace() was added in dot net 4: [http://msdn.microsoft.com/en-
us/library/system.string.isnull...](http://msdn.microsoft.com/en-
us/library/system.string.isnullorwhitespace\(v=vs.110\).aspx)

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

~~~
Someone1234
> 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.

~~~
eogas
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?

~~~
ygra
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.

------
fekberg
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](https://www.youtube.com/watch?v=BA3sL783_Co)

------
mkhalil
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.

~~~
darklajid
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.

------
cesarbs
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.

~~~
noblethrasher
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)?

~~~
icegreentea
Yes, the backing field is readonly.

------
BinaryIdiot
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.

~~~
keithwarren
Crazy, that will never happen :)

~~~
molmalo
[https://news.ycombinator.com/item?id=8595905](https://news.ycombinator.com/item?id=8595905)

------
FlyingLawnmower
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.

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

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

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

