What’s New in C# 7.0
blogs.msdn.microsoft.com
blogs.msdn.microsoft.com
If only .NET had a suitable cross-platform UI toolkit, then I'd be using it everywhere. Eto.Forms is a good attempt but I found rather buggy and limited at this point in development. Avalonia, while further along in terms of stability and features, doesn't even try to fit in with any platform's look and feel.
Correct me if I'm too excited, but won't these be an excellent alternative to maintaining lots of DTOs for SQL calls?
That's a good thing.
> or Mac OS X
"Does Winforms run on OSX?
Yes, as of Mono 1.9, Winforms has a native OSX driver that it uses by default"
http://www.mono-project.com/docs/faq/winforms/
> it looks completely out of place on Linux
On KDE3? KDE4? KDE Plasma? Gnome2? Gnome3? MATE? Cinnamon? LXDE? LXQt? Xfce? CDE? GnuStep? Unity? Enlightenment? Non-DE X Window System environment - with which Window Manager, with which theme?
> In terms of integrating visually with the desktop, we currently ship with a classic Win32 theme.
That sticks out like a sore thumb everywhere, including every Win32 release since Windows 2000.
That's a huge line to cross though! Once you give it a name then you generally have to give it a home somewhere.
No language has every feature. C# is making enormous strides ahead of many of its counterparts.
https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.1...
Namely, heap allocation and the inability to name tuple members.
Type inference FTW.
using Complex = System.Tuple<double, double>;
Edit: Clarity
using Complex = System.Tuple<double, double>;
is less verbose than public class Complex
{
public double i { get; set; }
public double j { get; set; }
} public class Complex {
private readonly double _i;
private readonly double _j;
public double I {get {return _i;}}
public double J {get{return _j;}}
public Complex(double i, double j){
_i = i;
_j = j;
}
}
But System.Tuple is also IComparable, IStructuralComparable, IStructuralEquatable. I haven't had enough coffee yet to add all the boilerplate for that to the above, which only reinforces the point about verbosity. public class Complex {
public double I { get; }
public double J { get; }
public Complex(double i, double j) {
I = i;
J = j;
}
} public class Complex {
public double I { get; private set; }
public double J { get; private set; }
public Complex(double i, double j) {
I = i;
J = j;
}
}In the .Net/VisualStudio world, the language tooling (Intelisense, visual drawing XAML & WinForms, etc) became as important as the language semantics or the availability of frameworks and documentation.
A long ago there was a fad, known as CASE (Computer Aided Software Engineering) that advocated doing on programming what CAD did to other engineering. It seems that were finally getting there.
Consulting has me moving jobs a lot and I encounter a veritable kaleidoscope of crappy work. Being able to correct minor issues in scope without restarting, while ten form posts deep in an archaic webforms app with dodgy "we-didnt-know-so-we-rolled-our-own" state management has been a lifesaver. Thank you nineties VB team, it's because of you that I'm not rocking back-and-forth in a padded cell making animal noises today.
In Eclipse (for example) you just start typing code, (none of this silly locking the IDE while debugging stuff), and the debugger will update the running program instantly. With jRebel you can even change things structurally without restarting.
Oh how I would love an actually working hot swap feature for .Net.
I only ask as I can usually manage 32-bit builds on dev while working, then just test there's no spooky differences when I target 64-bit.
There are issues with some projects that aren't well documented. E+C on web apps on local or remote IIS are a no-go (at least to the best of my knowledge), whereas if you can target IIS express during development it works beautifully.
I've always found that the juice has been worth the squeeze, for values of squeeze that only require me to tweak configuration for my dev box.
I'm not sure about other languages, but with Erlang's hot loading (plus the sync[1] project) I find that aspect to be nearly as good as E&C in Visual Studio.
While it's not quite at the level of 'stop the code from executing, changing something, continue', it's close enough for practical usage - save a file, the underlying module is more-or-less instantly recompiled and loaded.
Delphi was much better.
In the end, I found it hard to do maintenable code for complex applications. And it was not specifically because of the IDE but more because of the way you have to organize the code.
But I did not spend more than some months on it so maybe I'm wrong.
And they did actually. Windows Mobile - the original Windows Mobile, 2000-2012 - had 42% smartphone market share in 2007, a native Win32 API (and .Net Compact Framework for C# and VB.Net too), had WinCE kernel and worked on x86, MIPS, ARM and SuperH CPUs.
All what people like me want is NT kernel, Win classic UI, WinAPI with transparent JIT of x86 exe applications on a mobile device (like WinNT on Mips or DECAlpha or OSX Rosetta). And no nonsense like the metro crap from Win8/10.
I loved it until the 'trendy' movement toward fingers-driven UI started, around version 6.0.
If you had an large old Vb6 project build using MVP pattern you would be laughing.
Much like any other project in any other language.
Yes, you can write good or bad code in any language. But some languages have an endemic culture of not caring about good code. IME, VB is one of them, as is PHP.All the VB6 code I've seen has been a random mashup of databinding directly to the and click handling. The tools encouraged this approach.
I've certianly seen lot's of terrible VB6 code, but also lots of Vb6 apps that were better designed than some WinForms C# apps I've seen. I know this is all subjective.
I have learned the hard way that they don't care one single second about quality, only that it works the way required to support business, anything else is secondary.
In such environments even root access is time limited to a few hours and requires a ticket asking for it with a reason that should be validated by the boss.
That is what I was doing on Windows 3.x and have done while coding in Mac OS X and Windows.
Also the reason I never quite adapted to UNIX mentally of VI/Emacs.
Even though I have spent enough years coding for UNIX that me and Emacs are quite old acquainted with each other.
I know the essential for when Emacs isn't available which is quite common on commercial UNIX installations, learned back when Xenix was still being sold and don't intend to learn more than that.
Thanks anyway, I know you had good intentions.
I can write server-side C# in vim (without omnisharp) just fine, actually.
Maybe the tools became "indispensable" because they add value? I refactor my code in vim but it would probably be faster in VSCode. That doesn't make C# a bad language.
The var keyword was the first time it was even possible to write C# without tooling. It has definitely made it possible for me to use Vim for editing C# code. Newer features, such as lambda expressions, and some of the much nicer property syntax makes me feel that it may actually be fun to write C# from scratch without Visuak Studio looking over it.
I always thought of C# as the improved, less verbous Java. I wouldn't compare it with Python or other dynamic languages, but I prefer it to most compiled languages (especially at the times it was created)
public static IList<Ephraimite> FindEphraimitesToKill(IList<Ephraimite> ephraimites)
{
IList<Ephraimite> ephraimitesToKill = new List<Ephraimite>();
foreach (Ephraimite ephraimite in ephraimites)
{
if (ephraimite.Speak("shibboleth") == "sibboleth")
{
ephraimitesToKill.Add(ephraimite);
}
}
return ephraimitesToKill;
}
Now, the same in (imperative-style) OCaml: let findEphraimitesToKill ephraimites =
let ephraimitesToKill = ref [] in
List.iter (fun (ephraimite) -> begin
if speak(ephraimite, "shibboleth") = "sibboleth" then
ephraimitesToKill := !ephraimitesToKill @ [ephraimite]
end) ephraimites ;
ephraimitesToKill;;
See how much less we had to specify the type of what we're handling here? And things would have gotten easier if we used functional-style OCaml, but that's not entirely a fair comparison.So hypothetically it should be possible to write a C# compiler that would, if type annotations were omitted in some places, be confident enough to assign a sensible default, which is why we call the current version verbose. Although I suppose it's slightly more complicated than that. (Interfaces, if we want to have them, need to be explicitly declared as there are potentially many interfaces that could be used for a given object, and the rigidity imposed by redundant type declarations could help with the health of large and long-lived codebases.)
public static IList<Ephraimite> FindEphraimitesToKill(IList<Ephraimite> ephraimites)
{
var ephraimitesToKill = new List<Ephraimite>();
foreach (var ephraimite in ephraimites)
if (ephraimite.Speak("shibboleth") == "sibboleth")
ephraimitesToKill.Add(ephraimite);
return ephraimitesToKill;
}
or: public static IList<Ephraimite> FindEphraimitesToKill(IList<Ephraimite> ephraimites)
{
return ephraimites.Where(e => e.Speak("shibboleth") == "sibboleth").ToList()
}
is not that verbose.The C# style guide of a former employer of mine (an enterprise C# user) forbids both of these snippets because of the unbraced statements in the former and the LINQ and lambdas in the latter. But admittedly I don't know what's common among C# users, so maybe they were in the minority.
The "required brackets" is more common but I think it's a good rule :). Readability is only slightly hindered by the extra brackets, but I've seen quite a few errors from
if(shibboleth)
DoSomething();
DoSomethingElse();The LINQ version should be allowed almost everywhere that has a good development group. Sometimes LINQ queries can get hairier than the equivalent foreach, but I've never worked anywhere that would frown upon the shorter/cleaner LINQ.
I don't like the version without brackets, but I don't think it would make the code less compact if you'd add brackets.
Intellisense has become it's own lightweight thing and consumable from more tools, you can code just fine without it. ReSharper I've never used, I find it gets in my face more than it helps.
If you want to see a tooling based approach, go look at the state of android development these days. That's why we see stuff like react native becoming popular.
> My go to migrator is fluent migrator (https://github.com/schambers/fluentmigrator) or flywaydb if anyone objects to the c# (https://flywaydb.org/).
I don't think they will become as popular as red gate. Since you have to write the migrations yourself. That's a lot of additional work.
I also think your over estimating the popularity of red gate. A minority of places use it, whereas a lot use EF migrations.
I've never had an issue with it, If you make sure your database is constantly up to date. So changes are small.
I've had the opposite experience, I've only been at one place that used it and a couple that considered it.
> I've never had an issue with it, If you make sure your database is constantly up to date. So changes are small.
This is not an option in many places, if you have 3 month release cycles for instance (although I favor continuous deployment). Another is when you have apps installed on site, some clients can be multiple versions behind.
Then again, you don't have to always go for the most elegant/compact thing, either.
In F# these are "guaranteed" to be non-null, even though null instances come up during deserialization all the time. In C# use cases, I don't think the non-null "guarantee" should be made or implied, just a POCO.
You can see (and participate in) the discussion on records here if you'd like: https://github.com/dotnet/roslyn/issues/10154
> Seems like it'd be a cinch to implement
Ah... how i wish that were so :)
I'd love it if record definitions were extensible (even abstractly--sometimes you want a record with just the data, and sometimes including db-centric "id, createdTime, etc"), and there should be a way of defining / converting between them without a ton of boilerplate. That would allow something like:
record DbStuff = { id: int; created: DateTime }
record UserRecord: DbStuff { name: string; ... }
var userRecord = new UserRecord(...)
var userData = userRecord.WithoutDbStuff() // but what would be the reflected name of this type?
var newRecord = userData.WithDbStuff(3, DateTime.Now)
----
Sometimes you want to be able to define records
PhotoData{source, metadata, yada, etc, url} and
PhotoDisp{source, metadata, yada, etc, bytes}
without the repetition, and again with an easy way to convert between the two. (And yes you could simplify the above by using containership but oftentimes there are cross-cutting things that containership doesn't solve. You really want a flattening solution.)
Easy integration with C# anonymous classes should be considered too.
C# has always been the more real-world-centric language so I'd hope these common use cases would be considered.
But some things feel a little bit rushed:
- In the example "(o is int i || (o is string s && int.TryParse(s, out i))": When reading this statement as a human, o is obviously not an int when it comes down to the TryParse function. But if the 1st part was removed, the 2nd part wouldn't be valid either. I know this is technically how declarations work and I don't have an idea, if there is a better solution for this, but it feels weird.
- The new features of the case statement are nice but the old syntax with the mandatory break is probably worth getting rid of. Especially since all cases share a scope, adding/removing cases is prone to errors. I'd love to see a solution similar to "catch".
- The Deconstruct method is introduced as a "magic name". No interface, no override, nothing... Even the return type is "void". Why not use something like "public out Point(...)" to keep it similar in fashion to the constructor. Other options may be something with "this" (like indexing) or "operator".
The page said for type patterns it will "test that the input has type T, and if so, extracts the value of the input into a fresh variable x of type T", so if o is an int it'll be extracted to a fresh int i with that value
But the out syntax in TryParse isn't the new one they mentioned, it's the current one that requires predeclared variables - to be new it'd be out int i or out var i. So i is already declared as an int before this code example? In that case how can the first bit work? Does it not create a "fresh variable" if there's already one in scope with the desired name and type? That could be quite confusing, usual behavior is to compile error if an inner scoped variable conflicts with an outer one, I'm not sure I understand why this should be different.
o is int i
is effectively: int i; // in the nearest enclosing scope
(o is int && (i = (int)o)) // in place of an expression
The "fresh" variable `i` is available for use elsewhere. If an `i` already exists in that scope (the block the `if` statement is in), that is a redeclaration of a variable which is a compile-time error.If the "is" expression evaluates to `false`, the variable `i` will not be assigned, however, it will still be declared. Attempting to use `i` if it is not definitely assigned is a compile-time error. However, you have the opportunity to re-assign it.
Some examples:
{
if (!o is int i) throw Exception();
use(i); // works: i is declared and always assigned
}
{
if (o is int i) { do_something(i); }
use(i); // compile-error: i declared but might not be assigned
}
{
if (o is int i) { do_something(i); }
else { i = 0; }
use(i); // works -- definitely assigned
}
Thus the example pointed out in the post boils down to this in C# 6: int i;
if (o is int) {
i = (int)o;
} else {
string s = o as string;
if (s != null && !int.TryParse(s, out i)) {
throw Exception();
}
}
// i is definitely assigned here.Collection initializers already rely on “magic names” (the `Add` method + `IEnumerable`), so I’d say that’s okay. It’s simply a compiler feature, after all.
There is precedence for this in the form of GetEnumerator and GetAwaiter.
var names = LookupName(id);
WriteLine($"found {names.first} {names.last}.");
It's leaky and should simply use the deconstructing syntax instead.I'm on the fence about the ref returns. It can lead to some fantastic performance improvements and enable otherwise unusable datastructures. But is C# really a language you want if that is important to you. Why not go all in a use a lib in C or C++ for the critical parts of the code?
I still miss better immutability support, and probably most of all, ability to declare something at non-nullable.
But that said, the update is a fantastic update to an already good language.
C# is used by hundreds if not thousands of games by ways of Unity and is therefore demonstrably good enough in this scenario. Furthermore, just because a language is not C++ does not mean you shouldn't take every opportunity to give programmers tools to write fast code - at the end of the day I doubt anyone would be interested in a language that is purposefully slow.
Performance was a core feature of the language (yes, yes, it's managed) from day 1 with unsafe - it's nice to see further improvements in that department.
Use C++ when you need to, definitely, but when you're copying about 256 bytes around for a trivial world-view-projection matrix multiplication[1] you have a problem.
[1]: https://github.com/dotnet/roslyn/issues/10378#issuecomment-2...
public sealed class ExtensionAttribute : Attribute { }
Even async/await comprises of a convention and an interface - I haven't tried it, but in theory using the CLR 2.0 TPL should bring async/await your project. So far as I know, the feature being used for ref returns has always existed for C++/CLR so this stuff should work on CLR 2.0 (although you will need the C# 7.0 compiler).There's a project out there that swaps the mono compiler with Roslyn and gives some nice edit and continue features for Unity.
> Computation is innovated thanks to gamers.
The same effect might benefit programming languages.
It's great to finally have tuples, but the c/java style syntax is showing it's age compared to something like scala which has return type declarations at the end, which I find much more readable.
Literal improvements will be a godsend for writing database migrations.
Ref returns and locals look like a source of constant headaches. It's much harder to reason with code when the data can be modified by random others bits of code. Currently I can look for all references to an array to find everywhere that modifies it now I can't.
> Out variables seem like a mis-feature, especially when they are adding a better alternative (Tuples) in the same release.
Out variables are really great when working with existing code that predates Tuples (for example, the entire BCL). We don't just introduce language features that will only work well for new code. We also want to make the experience of coding against existing APIs feel better.
> Ref returns and locals look like a source of constant headaches.
That 'headache' has to be weighed against the needs of some parties to write very fast code and to have as little overhead as possible. ref returns enables a much more pleasant coding experience that enables these sorts of speedups in these specialized scenarios.
> It's much harder to reason with code when the data can be modified by random others bits of code.
There is a simple solution to this of course, don't expose your data through ref returns :)
For many (likely most) developers, ref returns simply won't be something that ever hits their radar. Similar to stackallocs and other esoteric features, this is really a targeted improvement for people who really like working in .Net but are finding it hard to squeeze out essential perf in some core scenarios.
The .net runtime supports this features fantastically. We wanted to make it available to people who like the power and safety of C#, but occasionally need some low level hooks to get that extra perf boost as well.
I disagree on this point. If there is a language feature that has been superseded by a better alternative, continuing to add sugar to the old feature only serves to perpetuate its use.
It embiggens the language while providing relatively little value in return. Furthermore, it adds confusion as to what should be considered idiomatic.
Tuples and deconstruction are so clearly better than out variables, I would have thought it would make more sense to deprecate the "out" feature entirely. Or, at the very least, not make it easier to use them.
Awkward and outdated features should be painful to use.
I also felt that this was a very odd addition. Even odder, the article doesn't even list tuples and deconstruction first.
With tuples especially, it's even worse, because the method name gets squished between two very similarly looking ()s, which is very different from how methods have historically looked in code. If I were scanning code fast, I'm not sure I would even read it as a function declaration.
C++ adopted its "auto ... -> ..." syntax a while ago - granted, they had a forcing function in form of decltype(), but many people also use it for readability reasons with complex return types. I hope C# follows suit; or, better yet, comes up with a unified type-after-name syntax a la ES6, that can be used everywhere in the language, while retaining existing syntax for back-compat purposes.
public TResult SomeMethod() where TResult : (string name, int id)
public SomeMethod(bool b) -> (string name, int id) { ... }
However, this may be undesirable due to confusion with => for lambdas and expression-bodied methods, especially in: public SomeMethod(bool b) -> (string name, int id) => ...
: is the next obvious candidate, and would unify the syntax with TypeScript and many other languages. But given that it's already used for labels and named arguments, I'm not sure there's enough room there to reuse it also for types.:: is another decent choice in terms of familiarity coming from other languages (Fortran, Haskell etc). But, unfortunately, it's already taken for extern alias, and I don't think this could be easily disambiguated in many contexts.
Now, if this is narrowly scoped to method return type only (i.e. we're not trying to invent a syntax that could later be used in a similar way to swap the type and the name in other places, like arguments and variables), and only as a fallback for when the usual "Type Name" arrangement has poor readability, perhaps take a hint from Ada and reuse "return"?
public SomeMethod(bool b) return (string name, int id) { ... }
A tad verbose, but if it's intended to be used sparingly, primarily with tuple-returning methods and deeply nested generics, I think that's okay - tuples themselves are pretty verbose when components are named.Or maybe borrow "as" from VB? It looks like it could be extended to other kinds of declarations in the future in a straightforward manner, without conflicting with its existing use for casts:
// Just for method return types
public SomeMethod(bool b) as (string name, int id) { ... }
// For everything
public SomeMethod(b as bool) as (name as string, id as int) {
var x as float;
TryFoo(out var y as bool);
...
switch (obj) {
case foo as Foo:
...
}
} public SomeMethod(bool b) -> (string name, int id) { ... }
When was this added to c++? I think I need to brush up on my lower level skills. var x as int;
"var" makes it a declaration, so "x" is the identifier, and "as" has to be the type specifier. var x = y as int;
"=" clearly separates the identifier from the initializer, and the latter is an expression, so "as" is the cast operator.Similar reasoning applies to other places where the two can appear - function parameter list, return type, field and property declarations etc.
So far as I can tell, by the time we get to the point where "as" would be used to specify the type of the declared entity, we will already know that it's a declaration, and that the only other token that can follow in existing grammar is "=", "{", or "=>" (for variable and field initializers and default parameter values, property getters and setters, and lambdas and expression-bodied members, respectively), and none of these start an expression. In all other contexts, "as" would be an operator.
template<typename A1, typename A2>
auto foo(A1 a1, A2 a2) -> decltype(a1 + a2) {
return a1 + a2;
}I'm worried this could result in a loss of focus, you can't make everyone happy all the time. c# is a fantastic language to develop applications in (web or desktop) but it's never going to be the fastest language around or be a systems level language. For me some of the other features listed here (like immutable records) would be a much better fit for where c# excels already.
One of the reasons we are stuck with C and C++ is because other language vendors, including Microsoft, dropped the ball regarding performance of type safe languages.
Do you think C++ would have been kept around if Java and the CLR had been AOT compiled to native code with focus on compiler optimisations since day one?
I really appreciate the efforts of the .NET team in adopting the Midori lessons in the standard .NET stack.
Consider virtual generic methods, for example. If your set of types is not statically bound, you can't allocate the appropriate number of vtable slots in advance, because you don't know all the instantiations.
I was already using dlls with plugins in Windows 3.1 and C++.
For that matter, it doesn't allow any templates across ABI boundary, except when you manually instantiate them (extern template) - and then only for those explicit instantiations. So it is effectively impossible to have a generic C++ API using templates that is not statically linked.
Borland C++ for Windows 3.x had an initial implementation for templates as they started to be discussed at ANSI and also supported exporting classes across dlls, providing both producer and consumer were Borland C++.
Here is the link for the Borland C++ compiler documentation, I was actually using the Turbo C++ version for Windows 3.1.
https://archive.org/details/bitsavers_borlandborn3.1Programm...
The BIDS, Borland International Data Structures were the template based library that replaced the object based one and could be accessible as a DLL as well.
To export classes from DLL one would do something like
// On the DLL side
class _export MyClass {...}
// On the consumer side
class huge MyClass {...}
Described on page 336 of the manual.If you check the the templates documentation, the generated code code could be externalized, page 152, via the -Jgx.
I was only a BIDS user across DLLs, but I can easily imagine a combination of _export/huge and -Jgd/-Jgx being what was necessary to make it all work.
"it doesn't allow any templates across ABI boundary, except when you manually instantiate them (extern template)"
So you can export template instantiations, yes. But you cannot export the template itself. For fairly obvious reasons - to instantiate a template requires compiling C++ code after substituting the tempalte parameters, so to export it across ABI boundary would require including the entirety of the C++ language (or at least a substantial subset - I guess you could desugar a bunch of stuff like, say, lambdas before) in that ABI.
And virtual templates are a whole other kettle of fish, because every instantiation of a virtual template would require a new slot in the vtable - or else the generic would have to dispatched by a single method, and the caller would have to supply runtime type information. In practice, C++ just forbids virtual templates outright.
In C#, this all works just fine, because generics still exist on bytecode level, which is what gets exported - and at runtime, the JIT will instantiate the generic by compiling that bytecode to native code, separately for every instantiation (in practice they unify them for reference types, because pointers are always of the same size; but value types get distinct JIT-compiled versions each).
For virtual generics, I'm actually not entirely sure how this works, but I would assume that vtable slots are allocated in batches and filled with instantiations as needed - and when you run out of slots and need to reallocate the vtable (and potentially shift indices of other methods in it), you can just JIT-recompile the bytecode for any method that happens to use the class with affected vtable.
There are many pieces of code that you probably use every day that go to great lengths to squeeze as much power as possible. Why not help these folks help us? I'm glad there is more focus on performance because we all benefit. (Hoping to see more on the CLR side.)
Rust or D seem like the best bet here
What is missing is a company like Microsoft to push it down to mainstream developers, at all costs, like it happen to all luddites.
Try OCaml.
Use a tractor.
Note: it's not like you can just sprinkle 'ref' on the return type of your methods willy nilly. Like 'ref'/'out' parameters, it requires you to do very specific things to keep your code safe/legal. As such, it's unlikely to just be added by people because, by and large, most code won't be equipped to actually handle it properly.
The codebases that will want to use this are already ones that have done a lot of work that makes them amenable to ref. i.e. game engines where you have large arrays of structs that you want to operate on in an efficient manner and whatnot.
I like the way its implemented in Perl. Use 'use strict' by default, and guard the block where you really need something unusual by 'no strict something' - refs, vars, subs - so neither compiler nor people reading your code never being confused whether is it a mistake or author's intention.
#pragma warning disable ${list of warnings}
and #pragma warning restore ${list of warnings}
https://msdn.microsoft.com/en-us/library/441722ys.aspxAlthough frankly the list of warnings to disable and restore consists of warning numbers, not names, which is not super convenient.
You can't retro-fit multiple-returns (via Tuples) onto existing library functions, so for places where you're forced into using out parameters, this is a slight improvement.
TReturn Foo(T1 param1, out T2 param2)
can be called as if it were (TReturn, T2) Foo(T1 param1)
You'd need a keyword to trigger this kind of overload resolution at the call site to ensure back compatibility - maybe you'd have to call (var x, var y) = out Foo(param);
or something. That way all that legacy library code gets a free upgrade to your new language feature.Since the C# team decided not to do that, you can actually implement a version of this at a library level, by static importing a family of generic methods like this:
Func<TParam, (T1, T2)> Tuplify<TParam,T1,T2>(Func<TParam, out T1, T2> outFunc) {...}
for every pattern of out params you want to convert, then you can just call (var x, var y) = Tuplify(Foo)(param);Scala or .... VB.net!
-Anthony D. Green, Program Manager, Visual Basic
IEnumerable<Student> GetStudents(SqlCommand cmd)
{
var rdr = cmd.ExecuteReader(); //select * from student left join courses on...
var memo = new Dictionary<int, Student.Completion>(); //Completion lets us add courses to a student
while(rdr.Read())
{
if(!memo.TryGetValue(rdr.GetInt32("student_id"), var out complete)
memo.Add(new Student(rdr out complete).ID, complete);
complete.AddCourse(rdr); //might be a no-op
}
return from kv in memo select kv.Value.Student; //each student object is unmodifiable.
} if(!memo.TryGetValue(rdr.GetInt32("student_id"), var out complete)
memo.Add(new Student(rdr out complete).ID, complete);
I think I understand your point, but I found this code really hard to read. You don't use the first var out complete in the TryGetValue, right? And the Student c'tor returns itself as an out parameter?If I understand you correctly, you like this because you don't have to declare a new student before you add it? I.e. the alternative would be
if(!memo.ContainsKey(rdr.GetInt32("student_id")))
var student = new Student(rdr);
memo.Add(student.ID, student);
I guess I would prefer this over the former. Also, why not enforce your student ID constraint in SQL instead of putting everything in a dictionary only to take it back out again? That would simplify your code to the point of just being a map from rdr->Student. Furthermore, if all I had was the Student c'tor, I would never guess that was the intent of the out parameter. This seems more anti-pattern than pattern.I would rather put a simple IEnumerable in front of SqlDataReader so that you could just do:
foreach(var row in rdr) yield return new Student(row)
This doesn't obviate your use case, however, which is to inline a variable where it's needed in multiple places in that line because you can save yourself an explicit declaration. In this case, however, I think that the increased readability justifies the explicit declaration.> You don't use the first var out complete in the TryGetValue, right?
There is only one complete variable; we declare it in TryGetValue, and it's definitely used in the last line of the while statement, but might first be used after the if statement.
> And the Student c'tor returns itself as an out parameter?
The Student constructor does not return itself as an out parameter, rather it returns an object that can modify an internal list of courses.
The idea is that when we iterate through a result set from a database, some of the rows are going to correspond to a new student object, and some are going to correspond to a course that belongs to the student. Crucially, we are only allowed modify the Student object (or whatever) during iteration, and the collection that we return will only contain immutable/unmodifiable Student objects.
I've used this technique to populate deeply nested structures (lots of joins and nested joins) using only one query.
> I would rather put a simple IEnumerable in front of SqlDataReader so that you could just do:
> foreach(var row in rdr) yield return new Student(row)
Just to be clear, the reason that I cannot do that is because the Student object might not be completely "hydrated" until we finish iterating through the result set, because it might contain a bunch of nested objects that also need to be instantiated from one or more DB records.> Also, why not enforce your student ID constraint in SQL instead of putting everything in a dictionary only to take it back out again?
I'm not quite sure I understand this (which is probably my fault), but rest assured that we use nothing but SQL (specifically, DDL) to enforce data integrity.
Back to this code:
if(!memo.TryGetValue(rdr.GetInt32("student_id"), var out complete)
memo.Add(new Student(rdr out complete).ID, complete);
There's a parens missing on the end of the if, correct? Also I can't parse the student c'tor: new Student(rdr out complete)
I was assuming there is a comma in there somewhere. Does this compile? What does "out" do here? I thought you were getting a new out variable, but that's not correct since you wouldn't be able to name it the same in the same scope.Also, I don't see how "complete" is ever non-null. If the ID isn't in the dictionary, then TryGetValue returns false and "complete" is null. Then you add the null "complete" to the dictionary, and throw away the Student object (which apparently does other side effects) once you have its id? If ID is in the dictionary, you get back what you inserted, which is still null.
And then you call .AddCourse on the possibly null reference? I'm lost.
Can you post the code again? Maybe I'm just missing something due to a syntax error.
Here is the equivalent C# 6 version of the code (i.e. something very similar to the pattern that I currently use):
IEnumerable<Student> GetStudents(SqlCommand cmd)
{
var rdr = cmd.ExecuteReader();
var memo = new Dictionary<int, Student.Completion>();
while(rdr.Read())
{
Student.Completion completion; //this declaration will be unnecessary in C# 7
if(!memo.TryGetValue(rdr.GetInt32("student_id"), out completion))
memo.Add(new Student(rdr, out completion).ID, completion);
completion.AddCourse(rdr); //completion is *guaranteed* to be non-null
}
return from kv in memo select kv.Value.Student;
}
As you can see, it only differs from the C# 7 version by one line.The first thing to note is that, per the C# spec, the `out` parameters of a method must be definitely assigned before the method returns[1]. It just so happens that the constructor of the `Student` class always creates a new `Completion` object and assigns it to the `out` parameter. Now, theoretically, an `out` parameter could be assigned a null reference (as in the case of TryGetValue), but in practice it's trivial to guarantee that it will be non-null (as in the case of our Student cstor).
In the line,
memo.Add(new Student(rdr, out completion).ID, completion);
we first call the Student cstor, which assigns a non-null value to completion, so that by the time `memo.Add` is called, the completion variable is guaranteed to be non-null.Also, `Student.Completion` is a class that is defined inside of the `Student` class. As such, it has access to all of Student's members (private and public). But, in order to do anything to an instance of Student, a Completion instance must have field which references that Student instance (unlike the case of Java's inner classes, which are a bit more powerful I think). That is why this line is possible:
return from kv in memo select kv.Value.Student //`Value` is an instance of Student.Completion
Here is the basic definition of the Student class: sealed class Student
{
public int ID { get; } //this is a readonly property, meaning it can only be modified in a cstor
public FullName { get; } //readonly property
private List<Course> courses = new List<Courses>();
public IEnumerable<Course> Courses => from c in courses select c;
public Student(IDataReader rdr, out Completion completion)
{
ID = rdr.GetInt32("student_id");
Fullname = rdr.GetString("fullname");
completion = new Completion(this);
}
public sealed class Completion
{
public Student Student { get; } //readonly property.
public Completion(Student student)
{
this.Student = student;
}
public void AddCourse(IDataReader rdr)
{
if(rdr.GetInt32("student_id) == Student.ID)
student.courses.Add(new Course(rdr));
}
}
}
Like I said in my earlier comment, my immediate goal was to be able to create a set of immutable objects with arbitrary nestings from the result of a single SQL query that may have an arbitrary number of joins (which is how we represent nesting relationally). The above example just has just one nested property, but I have production code in which objects have many more nested properties. For example, the `Course` class in the aforementioned example might have its own `Completion` class for adding `CourseAssignment` instances (e.g. select from Student left join Course on ... left join CourseAssignment on ...).But, the really big idea is that I wanted an object-capability system[2][3]. Getting objects be immutable "almost everywhere"[4] is a nice side benefit.
[1] http://www.ecma-international.org/publications/files/ECMA-ST... (section 12.1.6)
[2] https://en.wikipedia.org/wiki/Object-capability_model
[3] https://www.youtube.com/watch?v=EGX2I31OhBE
[4] https://en.wikipedia.org/wiki/Almost_everywhere (in this case "almost everywhere" is with respect to the set of all possible execution paths).
StudentId| Name |CourseId
============================
1| Bob| 1
2| Jane| 1
1| Bob| 2
1| Bob| 3
2| Jane| 4
With many more columns of course. The point being that it's a denormalized listing of student-course pairs. If so, you'd be able to get immutability by reading the query result into a data table and doing something like: var result = from row in dt.AsEnumerable()
group row by row.Field<int>("StudentId") into grp
select new Student(
grp.Key,
grp.First().Field<string>("Name"),
from courseRow in grp select new Course(courseRow)
);
This seems to satisfy all of the conditions that you list (namely immutable objects), but with the added advantages of not needing a inner Completion class, and a number of less lines of code.Furthermore this is less coupled because now the Student class doesn't need to worry about DataReaders or DataTables or which column names to read from.
I would also argue that this version is a lot easier to read and reason about.
I think you could make a similar transformation for any circumstance in which you wanted to use an out variable in the fashion you outline.
Does that make sense? Is there another case in which you would advocate for our variables in new code?
Can you elaborate on this; both how it helps and why you're using C# for database migrations?
Each migration gets a number, typically time encoded. If I was to write one now it would have the attribute [Migration(201608251157)]. With the new literals this will become [Migration(20160825_1157)], amazing how much readability a single underscore can make.
I hope there are better examples of Scala's syntactical advantages than this one, because it seems like the 'egyptian-style' vs 'next line style' brace bracket debate...
match(shape)
{
case Rectangle r
return r.With*r.Height;
case Circle c
return pi*c.Radius*c.Radius;
} int myvar, I;
foo(out int mvar); // oops, not myvar; maybe caused by a refactor?
bar(out *); // oops, not I; was up too late coding
And so on. Things like this would be easily missed when reading code at-a-glance, and it's this sort of bug that arises often in languages that allow implicit declaration of variants.I don't really see your example in that way. Let's start with the latter one first:
> bar(out *); // oops, not I; was up too late coding
I'm not sure how this situation is any differnet from any other case where you need to pass some variable, and you pass the incorrect name. This is already possible all over the language. For example, you might have written "bar(out J)" when you meant "bar(out I)". As usual, the recommendations here are to use strong types and good names to help keep your code clear in intent and to allow the compiler to tell you when something seems awry.
Now let's look at your first example:
> foo(out int mvar);
This version immmediately screams at me that something is happening that requires my attention. First off, just the presence of 'out' is an immediate call that this is not a normal call. Nearly all calls pass by value, so out/ref stick out like a sore thumb (esp. in an IDE that classifies them accordingly). Second, the "out int" is another large indicator that this is doing stuff very special.
Finally, i'd point out that the mispelled name problem is really no different than what you might experience today with code like:
int myvar;
...
// much later and indented a bit ...
int mvar;
Foo (out mvar);
Here you've unintentionally introduced a new variable that you may or may not have intended to. Without a collision, there's no way to tell.> it's this sort of bug that arises often in languages that allow implicit declaration of variants.
No implicit declarations are allowed. All declarations are explicit. We just don't force you to have to declare in one location and use in another. This is a pattern that many people hate, and which goes against a desire to immediately declare and initialize, and thus not have to track down how a variable is written to.
It's a wildcard. Passing in any other variable name would ideally raise an error about the use of an undeclared variable or a mismatched type. The use of a wildcard disposes of those errors.
> the mispelled name problem is really no different than what you might experience today
Not quite; your modified examples includes two declarations on their own lines. Being on their own line gives them greater visual presence at-a-glance than the new syntax which buries the declarations within a parameter list.
Worth noting is that my trivial example managed to confuse at least one reader who was unable to see the issue[0].
> All declarations are explicit.
While true, you've muddied the lines a little by moving declarations into the syntax of other expressions. Where previously a declaration sat on its own line or at the beginning of an assignment, they may now be peppered throughout the syntax in ways that are not so easy to observe at-a-glance.
I'm not happy about wild cards. It seems like taking what is a very powerful character in software development and using it for a pretty minor usability improvement. Besides it seems misleading. When I see an asterisk I don't think throwaway. I can see how that aligns with "anything can go here" meaning from regex, but I feel there is a difference in "value". Using a * in a regex seems to increase the power and heft of the regex, where as using it here, seems to decrease the value, which is almost the opposite effect. Another way of putting it is that the point should be to let me ignore this while reading code, but the asterisk draws my attention to it instead.
Compare this to the Haskell convention of using an _ for throwaway items, which disappears just enough, instead of attracting attention. And by simply being a convention, it isn't giving the character too much power.
Not sure if lack of Haskell style type inference prevents C# from using convention for throwaways instead of wildcard chars, but I think it would be much less overhead on the Dev.
You'll get a compiler error if you try and use `I` uninitialized.
Not saying you're wrong, just having trouble getting worried about this. You can make typos now:
int x, y;
foo(out x, out x); // oops, not y; was up too late codingSure, you can make typos now, but these changes expand the possibilities of errors arising from typos or incomplete refactoring; while reducing the discoverability of the issue at-a-glance.
This should fail to compile, it's the equivalent of declaring a variable twice int the same scope.
This resulted in many cases that those methods needed to be broken out into their own class... which is the way to go some times but felt like a bit of overkill in others
If you really wanted to, wasn't it already possible to create anonymous delegates/lambdas locally? The only improvement I see with local named methods are readable stacktraces.I have to admit, the mangled names are a major headache for me (and the stacktraces starting at lamda invocations, missing the 'original' stacktrace. I'm looking at you Parallel.Foreach!)
I'd be happy with either extension methods with state or adding traits to the language as a separate feature. I understand the reasons it was decided against in C# 4, but its hard to preach composition over inheritance when the framework is philosophically against it, and it runs contrary to how the whole framework is structured (single inheritance from Object). But it still irks my fussiest self.
You can get something that sort of gets mostly there with ConditionalWeakTable, but its not endorsed by the vendor, and in the experience I had with it while trying to create a mixins module for C# a few years back, makes the GC leak like a sieve at scale.
GetCoordinates(out var x, out var y)
over destructuring assignment like var x, var y = GetCoordinates();
the former looks completely backwards.IMO fishing parameters back from functions is one of the things I do not miss from old C.
Anyone has anything to add to masklinn's explanation?
Edit:
found CyrusNajmabadi's comment here: https://news.ycombinator.com/user?id=CyrusNajmabadi
This way you would get a Boolean if the coordinates exist and would not have to perform validation on the out variables.
eg. in C++: tuple<int,int> x = GetCoordinates(); or auto x = GetCoordinates()
Much easier to see the output. I maintain enough old old C++ code and don't like seeing GetCoordinates(int x, int y) or x in COM-land any more.
http://stackoverflow.com/research/developer-survey-2016#tech...
In preparation, the feature currently called "anonymous classes" in C# needs to be redubbed "anonymous records". And in preparation for that, well, "nonymous" records need to be introduced.
Googling that term just gives a whole lot of references to inner classes in Java.
myButton.AddListener(new Command {
bool enabled() {
return false; //more logic goes here
}
void onClick() {
//do something
}
}); SubmitCommand = new DelegateCommand(()=> DoSomething(), ()=> IsSubmitEnabled);
Edit: and obviously the Command DependencyProperty on the Button will be bound to the SubmitCommand property, instead of accessing directly the button from the ViewModel, that is the worst possible thing that you can possibly do."Switch statements with patterns
We’re generalizing the switch statement so that:
•You can switch on any type (not just primitive types)
•Patterns can be used in case clauses
•Case clauses can have additional conditions on them
Here’s a simple example:
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}There are several things to note about this newly extended switch statement:
•The order of case clauses now matters: Just like catch
clauses, the case clauses are no longer necessarily disjoint, and the first one that matches gets picked. It’s therefore important that the square case comes before the rectangle case above. Also, just like with catch clauses, the compiler will help you by flagging obvious cases that can never be reached. Before this you couldn’t ever tell the order of evaluation, so this is not a breaking change of behavior.
•The default clause is always evaluated last: Even though the null case above comes last, it will be checked before the default clause is picked. This is for compatibility with existing switch semantics. However, good practice would usually have you put the default clause at the end.
•The null clause at the end is not unreachable: This is because type patterns follow the example of the current is expression and do not match null. This ensures that null values aren’t accidentally snapped up by whichever type pattern happens to come first; you have to be more explicit about how to handle them (or leave them for the default clause).
Pattern variables introduced by a case ...: label are in scope only in the corresponding switch section."
type Tree<'a> = Empty | Node of 'a * Tree<'a> * Tree<'a>
There is no way to express this directly in C#. Thus, I am "locked out" of a whole class of Pattern Matching that I would get with F#.But that doesn't mean that C#-style pattern matching (really, Is-patterns and a Type Switch) don't fall under the umbrella of Pattern Matching. You can define tuple patterns that you can match on with the switch statement in C#, which is every bit a form of pattern matching as matching on a particular case of a union type.
I'm afraid that is not the case, because in the current C# version, the compiler does nothing help you determine if you've matched all the possibilities. (it is not exhaustive)
Exhaustiveness is important because it gives warning or an error to help you refactor and modify code without fear of breaking other code. Why engage in all the static typing business if the compiler is not going to help you refactor things?
This is important in the same way that adding a subclass requires exhaustively supplying all the abstract methods (true pattern matching is "dual" to adding a subclass; you use the compiler feedback to direct what actions to take next. you can't do this with the Switch based formulation because you don't get any feedback from the compiler if you missed cases or have refactored other code to add cases (for example, adding/refactoring abstract methods in a base class provides feedback on where to add/update methods in the subclasses)
I agree with you that exhaustiveness is incredibly important, and I really hope that it can be done in C# some day. However, record and union types are also a piece of this puzzle.
I also think language level support for this would be a killer feature, it turns OOP and the requirement to use polymorphism to guarantee strategy-per-type on it's head.
Nonetheless C# is a nice language. I enjoy writing C# code, just as I enjoy writing Swift code.
(For starters, Swift desperately needs to include most of the points from "Generic Manifesto" to be comparable with more mature languages like C#. Not being able to return a generic interface from a function is just silly)
That's a pretty sweeping generalization. Most of the headline features in the article are already in other languages e.g. Scala.
I agree that C# is far more widely used than Scala, but Scala is being used by significant numbers of developers esp. for Spark. Tiobe is also widely regarded as a pretty poor indicator of language adoption.
I was hoping for deterministic lifetimes in this release.... just kidding. Must be me being used to C++'s RAII and useful destructors.
I believe your comment is a huge generalisation.
When using C# I'm constantly noticing how much extra code there is. It's just frustrating, and I don't feel like I'm getting a unique benefit in return (unlike, say, in Rust). I know F# would be more concise and work just as well. But I know it's not easy extending the existing design decisions.
(The tuple story is sad, eh? This was F#'s original design, using structs. Then they made peace with the strange heap allocated framework tuple. And now...? No tuple interop?)
Anyways, congrats, C# definitely is the best general dev language commonly accepted at a large amount of companies, especially when factoring in tooling.
Actually you are getting a benefit in return (unlike, say, in Rust) - the libraries. Verbose syntax is less complex in regard to writing the code, so more developers write the code. I have no scientific evidence to provide about the fact, but observations speak for themselves. Compare the quantity of libraries available for Rust and yet another 'overly verbose' language, Go. We can find Go wrapper for almost anything, and often a few to chose from.
Rust was stabilized last year, while Go was released six years ago. It is simply wrong to say that Go has a larger quantity of libraries because it is more verbose. IMHO the Rust ecosystem is surprisingly comprehensive for a language its age.
I think it's a problem that needs to be solved in the CLR, not C#, and my guess is it probably never will be.
What if instead of
if (o is null) return; // constant pattern "null"
if (!(o is int i)) return; // type pattern "int i"
WriteLine(new string('*', i));
somone forgot to return, as in if (!(o is int i)) {
// do something
}
// incorrectly try to use `o` as an int
WriteLine(new string('*', i));
Rust uses the special `match` syntax to avoid this. But I suppose C# 7.0 also analyse the structure of the `if`s and `return`s to acheive the same effect more flexibily.And if it can do that, could that they also start phasing in statically-checked null avoidance?
if (o is int i) { f(i); }
use_int(i); // <-- error: variable `i` is not definitely assigned
But then if you have: if (o is int i || (o is string s and int.TryParse(out i)) use_int(i);
We know that `i` is definitely assigned at that location. int i;
if (x == 3) { i = 2; }
WriteLine(i);
I'd be interested to hear the answer, though.In my ideal world, it'd look like...
switch (x)
{
case 1:
{
/* ... */
}
case 2:
case 3:
{
/* ... */
}
}
And before anyone points it out, switch is the same as else if when the thing being compared is a simple local variable.It's usually a good idea to create a new scope with your cases, so you can avoid some irritating variable name clashes, since, unlike and if, switch cases don't automatically do that, i.e.
switch(foo) {
case 0:
var bar = 2;
// do stuff...
break;
case 1:
var bar = 47; // error, conflicting variable name
// do stuff...
break;
}In other situations, you really don't want it to do that, so a break is required.
How would the compiler know the difference? Note that you can't "fall through" cases in Swift, and it is irritating. It stops you using the same code for two case statements - you have to duplicate it or put it into a function.
switch (x)
{
case 1:
{
/* ... */
}
break;
case 2:
case 3:
{
/* ... */
}
break;
}Break is there for a good reason.
I don't think I've ever seen a case where I wished for that feature.
All the other things - tuples, anonymous out vars, pattern matching - I've found myself wanting quite often.
1. Regex expressions just like Regexp in JS:
/^\s+$/.IsMatch(" "); // or
Regex r = /^\s+$/;
2. DateTime expressions, similar to regex, something like: DateTime clockTowerLightning = #1955/11/12 10:04PM#;I don't know about the current state of C#'s grammar, but ambiguities between this regex construct and eg. division contributes to the complexity of correctly parsing JavaScript code.
https://tc39.github.io/ecma262/#sec-ecmascript-language-lexi...
My main objection is over the month/day confusion with other formats. Is that November, or December?
Definition: https://gist.github.com/noblethrasher/5edffb4cb2efa4ed9174fb...
//Usage:
var is_match = " ".IsMatch("^\s+$");
//OR
regexp rgx = "^\s+$";
is_match = rgx.IsMatch(" ");But given the constraints of mscorp and the target users perhaps they made the right decisions.
def hello("sergio") do
IO.puts "Hello Sergio"
end
def hello(name) do
IO.puts "Hello #{name}"
end
---
hello("sergio") => "Hello Sergio"
hello("mia") => "Hello mia"http://elixir-lang.org/getting-started/pattern-matching.html
2#1010101
8#75342
1341235
10#13451
16#feb1300
radix#value, from erlang.Or:
#b10101
#xfefe
#o7777
#36rSSSS
From common lisp.Customize in some fashion for C# and its current notations for hex and (now) binary literals.
036rSSSS
02r10101
0b10101 // this and above are equal1. Our current base notation is already familiar and widely used. Nobody is confused about 0xA vs 0b10.
2. Nobody will really use those other bases, so you're adding obscure features that muddle your syntax.
We use VS2012
You just need to upgrade VS to 2015. Language version has nothing to do with framework version!
Last year we were still targeting XP.
Dependency Order Compilation
The only thing for F# is that F# allows the user to determine the compilation order and show it in Visual Studio.
"One of the most common complaints about F# is that it requires code to be in dependency order."
In light of your statement I understand the way I put it made little sense.
Can you give an example of where you'd want to take advantage of this in C#?
Thanks!
Old example:
bool Hello(string name) {...}
var myName = "world";
Hello(myName);
The developer can change the name of variables in the prototype to be more (or less!) descriptive without a problem - they're decoupled.New example:
(string interjection, string name) GenerateGreeting() {...}
var greeting = Greeting();
Console.Write("{0} {1}", interjection, name);
Now should the author change "interjection" to "greeting", _ your code won't compile _ and in a way that you likely didn't expect. string interjection;
string name;
(interjection, name) = GenerateGreeting() {...}
I can't believe the C# team would introduce something so brittle into the language. If you're right, that a serious concern.[edit] unless you're talking about how your example magically introduces "interjection" into the scope. That's not how it works. You would have to say "greeting.interjection". Or use the destruction syntax and say "var (ichosethis, andthis) = generateGreeting();", in which case its the order of the fields, not the name of them, that is important.
But that's the same as named parameter, and you didn't complained, if the client used named parameters and you change them it will break their code. The full signature of the method is the public API, as you can see when navigating a compiled assembly.
(string first, string last) name = GetName();