15 ms·
What's New in C# 6.0 [video]
- Tloewald 12y agoNothing 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 12y agoFrom 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.
- rzimmerman 12y agoIt 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.
- iaskwhy 12y agoYou can also view a summary of the video/features as a presentation: https://view.officeapps.live.com/op/view.aspx?src=http%3a%2f%2ffiles.channel9.msdn.com%2fthumbnail%2f6fcbe7ba-1cf1-4332-a9e3-ad559fe907c1.pptx https://view.officeapps.live.com/op/view.aspx?src=http%3a%2f...
- IanDrake 12y agoThanks. Looks pretty awesome!
- zak_mc_kracken 12y agoCan't get past slide 4 (blue spinning ball on the cursor, yay Office Live). Anybody have a pdf version?
- bogrollben 12y agoyeah that happened to me on Chrome. Try IE.
- ComputerGuru 12y agoHere you go: http://cl.ly/0C25161f2T1q http://cl.ly/0C25161f2T1q
- wideroots 12y agoworks perfectly fine on Chrome, IE, and Firefox.
- sootzoo 12y agoIt's also much the same content as: http://msdn.microsoft.com/en-us/magazine/dn802602.aspx http://msdn.microsoft.com/en-us/magazine/dn802602.aspx
- architgupta 12y agoThese 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).
- Griever 12y agoSeems like a small change but that nameof(argument) method for ArgumentXExceptions is incredibly handy.
- algorithmsRcool 12y agoAnd also for INotifyPropertyChanged! (Although CallerMemberName helped that some in C#5.)
- SigmundA 12y agoStill 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 12y agoI'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.
- jsmeaton 12y agoI 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.
- seanmcdirmid 12y agoI wrote a framework that wrapped dependency properties to accomplish things like this once: http://bling.codeplex.com 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/managedtime.aspx http://research.microsoft.com/en-us/people/smcdirm/managedti...
- pilif 12y agoBeing 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 12y agoGiven that the 'vanilla' async-await isn't always safe/bug-free, I can't imagine that the harder version will be.
- felixrieseberg 12y agoInterestingly, 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_ 12y agoI was hoping Unity would start loosing some market due to outdated Mono. I guess we are in for another github-like "monopoly".
- TillE 12y agoNah, 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.
- swalsh 12y agoIt's funny that of all those, i'm most excited about nameof
- hvs 12y agoThe 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 12y agoI 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?
- hvs 12y agoThat'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.
- Encosia 12y ago.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.
- Someone 12y agoEven 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)
- FlyingLawnmower 12y agoawait 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.
- JamesBarney 12y agoStill hoping they add the !(non-nullable) operator. I know its hard http://blog.coverity.com/2013/11/20/c-non-nullable-reference-types/#.VGY_5fnF-QA 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.
- pjungwir 12y agoIn 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.
- mytochar 12y agoRust'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.
- bjz_ 12y agoRust 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`.
- Someone1234 12y agoAren'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.
- zobzu 12y agoI'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 12y agoI 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 12y agoI 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 12y agoI'd love to be able to write drivers in c#.
- _random_ 12y agoXamarin for iOS compiles to native as far as I am aware.
- pjmlp 12y agoNative code will be supported across the board for Windows 10 devices, http://www.hanselman.com/blog/AnnouncingNET2015NETAsOpenSourceNETOnMacAndLinuxAndVisualStudioCommunity.aspx http://www.hanselman.com/blog/AnnouncingNET2015NETAsOpenSour... Unless Windows Desktop is meant as store applications.
- 12y ago
- BinaryIdiot 12y agoLots 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 12y agoCrazy, that will never happen :)
- molmalo 12y agohttps://news.ycombinator.com/item?id=8595905 https://news.ycombinator.com/item?id=8595905
- moron4hire 12y agoUsing 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 12y ago>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 12y agoIf 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 12y ago> 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.)
- wbond 12y agoWhile 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 12y agoAs 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.
- custardcream 12y agoWell 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-to-objects-to-extremes-a-fully-linqified-raytracer.aspx http://blogs.msdn.com/b/lukeh/archive/2007/10/01/taking-linq...
- V-2 12y agoOver the board or just expressive? http://programmers.stackexchange.com/a/261893 http://programmers.stackexchange.com/a/261893
- gavinpc 12y agoHa! "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.
- cesarbs 12y agoI 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 12y agoAgreed, 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 12y agoYes, the backing field is readonly.
- zer0nes 12y agoWhy don't you use public readonly fields?
- seanmcdirmid 12y agoInterfaces and overriding usually.
- noblethrasher 12y agoI'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 12y agoI've never seen the arguments for error codes vs exception. Care to explain briefly or link me some information?
- noblethrasher 12y agoHere'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
- sagivo 12y agoi love the new "?." similar to coffeescript. definitely make our lives easier.
- EStudley 12y agoI 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 12y agoTo be fair, the first time I saw this was in Groovy, almost ten years ago.
- cheapsteak 12y agoWhat is this called? It's impossible to google for
- grokys 12y agoInformally the "Elvis operator".
- zak_mc_kracken 12y agoCorrect: http://groovy.codehaus.org/Operators#Operators-ElvisOperator http://groovy.codehaus.org/Operators#Operators-ElvisOperator(?:)
- adrianmsmith 12y agoThe "Safe Navigation Operator" - http://groovy.codehaus.org/Operators http://groovy.codehaus.org/Operators
- mkhalil 12y agoIt 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.
- _random_ 12y agoGood for reflection and renames. ReSharper helps but I don't want to rely on it.
- miketesch 12y agoIt shouldn't have any efficiency implications. I have to imagine that it is interpreted at compile time, similar to the var keyword.
- nothrabannosir 12y agoIt's syntactic sugar, semantically equivalent: nameof(foo) <=> "foo" Efficiency doesn't change
- darklajid 12y agoHe 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.
- Someone1234 12y agoThey need to add these: https://github.com/MiniProfiler/dotnet/blob/master/StackExchange.Profiling/Helpers/ExtensionMethods.cs 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.
- ColinDabritz 12y agoIsNullOrWhiteSpace() was added in dot net 4: http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/system.string.isnull... I agree that Truncate would be a nice one to include in the core.
- Someone1234 12y ago> 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.
- samjltaylor 12y agoGood to see immutability being given some attention. Elvis operators though, I think they make code shorter rather than easier to understand
- IdleChris 12y agoWhat's new in VB 14 (video): http://channel9.msdn.com/Events/Visual-Studio/Connect-event-2014/113 http://channel9.msdn.com/Events/Visual-Studio/Connect-event-...
- edgyswingset 12y ago> New feature: Go To Definition Oh those poor, poor souls who have had to work in C#'s shadow.
- jsmeaton 12y agoNot knowing anything about VB these days, this video almost looks like satire :P
- jmartinpetersen 12y agoI'm sorry for my coworkers and whoever else around me - I will now shout "NEW FEATURE" constantly.
- louthy 12y agoI 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?
- mariusmg 12y agoBecause people like braces (they provide structure) and there is a risk to break backward compatibility. Granted the whole ;} = 5; syntax is not great ....
- louthy 12y agoThat 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.
- zer0nes 12y agopublic 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.
- 12y ago
- hkon 12y agoMore fun for the juniors who have just come to terms with the ternary operator.
- uniformlyrandom 12y agoIt has only been like 50 years since it was introduced. The juniors are coming to terms with retirement now.
- hokkos 12y agoBecause 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.
- fekberg 12y agoI 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
- zaroth 12y agoSo 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;
- coldtea 12y ago>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.
- coldtea 12y ago[Edit: this perhaps should have been "Changing semantics based on visual attributes is not"].
- DenisM 12y agoStill no first-class tuple support? Argh! All want is: var first, last = parseName(fullName); Instead of: String last; var first = parseName(fullName, out last);
- BigChiefSmokem 12y agoi 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
- DenisM 12y agoHaving 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.
- sootzoo 12y agoAgree 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;
- louthy 12y agoTotally 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