322 points · by runesoerensen · 10y ago · 268 comments
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?
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.
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.
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.
If you had an large old Vb6 project build using MVP pattern you would be laughing.
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)
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.
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)
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.
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.)
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.
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.
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.
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();