117 points · by yulaow · 12y ago · 65 comments
Does anyone know what the dollar syntax is? Similarly, the new dictionary initialiser syntax? Fisnlly, what is private protected?
Edit: these are from https://roslyn.codeplex.com/wikipage?title=Language%20Featur...
C# Dictionary initialization is currently something like this:
var d = new Dictionary<string, string>
{
{ "key", "value" },
{ "but this one", "has spaces" }
}
The new syntaxes appear to be these: var d = new Dictionary<string, string>
{
$key = "value",
["but this one"] = "has spaces"
}
(Also, with C# 6's new abilities around constructor type inference, the type parameters may now be superfluous. I'm not certain, though.)The access modifier "private protected" appears to mean "only derived types that are also in the same assembly."
It replaces a 'magic string' with a 'magic variable name', which is worse than the normal solution for magic strings, which is to move them to a constant.
If I have code in one place that says:
dict["key"] = "value";
and code elsewhere that says: var value = dict["key"];
I can make that code better today by adding const string KEY = "key"
and then using dict[KEY] in both places. I can change the key in one place, and if I misspell the constant name in either location then the compiler tells me I have a problem.With the new syntax, I can now write
dict.$key = "value";
and var value = dict.$key;
but if I go ahead and change one of these: dict.$newkey = "value";
I'm not going to get a compiler warning when I try to read $key (am I?). Unless there's some smart tooling support, where's the win here?Key symbols aren't becoming a new type - I don't get to write
var key = $key;
var big_key = ["key with spaces"];
(so far as I'm aware - though I actually quite like the idea of a datatype that represents this kind of non-manipulable string identifier)I guess the new .$ syntax combines with the null-propagating ?. operator, so you could have nested dictionaries and access them with:
dict?.$subdict?.$subsubdict
which looks... horrible. And suffers from the fact that there's no null-propagating equivalent index access operator, ?[], so I can only use this trick on keys that can be written as C# symbols.
I really feel like I'm completely missing what the use cases are for this capability...
var bigKey = $key_with_spaces;I don't understand the advantage of the dollar syntax though. One character shorter, and makes it look more object-y, obscuring the perf difference.
At least in python, I would love to have syntax like that. (I would use :: instead of .$, but maybe :: is already used in C#.)
Maybe it's just because I work with JSON a fair amount, but I frequently have an it-might-as-well-be-an-object that happens to be stored in a dict. And in theory, this means I need to do foo['bar']['baz'], which is hard to read and unpleasant to type. In practice, I often use a class which overloads attributes as being dict keys, so I can use foo.bar.baz, but this has its own problems. foo::bar::baz would be great.
So far null propagation seems like the most useful feature for cleaning up cluttered code I'm used to dealing with.
Auto-property initializers are nice, but the syntax looks a bit ugly and I don't see them making that big of a difference in readability. I would rather see something that tackles the ugly-but-necessary construct I see the most: lazy-loading getters. Generic memorization of methods and properties would be even more useful. And yet even more useful would be something that could be used for both memoization and transparent caching:
[Cache(For = 1000 /*milliseconds*/)]
public GetSomethingFromDB(){ ... }
That would be tough to implement well, though. Unless they added Python-like attributes. Which would give us memoization, caching an a myriad other things.The first one is an answer I wrote on SO and the other is a library I wrote a couple of years ago. Both are are different solutions to the caching problem you describe.
So in your example you could create one to detect your attribute and inject custom logic instead. You can unleash the full power of AOP at the compilation level.
private Lazy<string> _someVariable =new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
public string SomeVariable {
get { return _someVariable.Value; }
}
Imagine the same things with a long lambda inside.In languages that allow for full macros, many of those features can be implemented as library instead, which also creates the problem everyone has their own little DSL.
Anyway looking to the history of computing, all mainstream languages that started simple as a movement against complexity of some sort, ended up becoming more complex release after release.
Using static is great - finally we've liberated the verbs in the kingdom of nouns.
However, some of them have really ugly syntax. I know they wanted to get rid of the boilerplate problem of declaring and setting into a read-only member, but the primary constructor syntax is monstrous - declaring local variables inside of your constructor? Really? I feel like just having a "readonly set" access modifier on properties (both auto and explicit) would have been sufficient.
The new dictionary accessor seems silly.
Exception filters seem just as pontless in C# as they did in VB (nesting an "if/else throw" into a catch clause wasn't too hard).
The crazy null ?. operator I'm unsure about... that one I'll have to use. I've run into the problem enough times to see why they did it, though.
That is
catch(Exception ex) {throw;}
Rethrows without meddling with ex.
No it doesn't. If you then let that exception fall out as unhandled, the stack trace will be centered on the second throw, not on the original.
I really like the what the monadic null checking does but aesthetically it looks pretty ugly right now.
FYI, we have discussion threads on http://roslyn.codeplex.com.
Readonly properties require less syntax.
Before
private readonly int x;
public int X { get { return x; } }
The only scenarios where I require readonly properties are where I set or otherwise calculate a private variable at runtime, and then enforce readonly to the public getter.
In the example above, it looks like the private variable is readonly, and must therefore be initialized with a value that cannot be changed. Am I reading this correctly?
var success = int.TryParse(s, out var x);
I'm a bit 'meh' about Primary constructors, Auto-property initializers, Getter-only auto-properties. It seems a bit messy and incomplete. Personaly I don't use properties anymore and just use readonly fields with constructor initialisation (which is enough to capture the property setting logic). What I would like to have seen in this area is 'readonly' classes, with mechanisms for cloning objects using named parameters for partial updates: readonly class ReadOnlyClass(public int X, public int Y, public int Z)
{
}
Usage: ReadOnlyClass obj = new ReadOnlyClass(1,2,3);
ReadOnlyClass newObj = obj.X = 10;
Instead of the current system for creating immutable classes in C#, which becomes quite unweildy and error prone as the number of fields grows. class ReadOnlyClass
{
public readonly X;
public readonly Y;
public readonly Z;
public ReadOnlyClass(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
public ReadOnlyClass SetX(int x)
{
return new ReadOnlyClass(x, Y, Z);
}
public ReadOnlyClass SetY(int y)
{
return new ReadOnlyClass(X, y, Z);
}
public ReadOnlyClass SetZ(int z)
{
return new ReadOnlyClass(X, Y, z);
}
}
Usage: ReadOnlyClass obj = new ReadOnlyClass(1,2,3);
ReadOnlyClass newObj = obj.SetX(10);
I think 'using' static members will be a huge win for creating functions which appear to be part of the language. For example I use the following to do type inference on lambda expressions: static class lamb
{
public static Func<T> da<T>(Func<T> fn)
{
return fn;
}
}
var fn = lamb.da( () => 123 );
I'v tried to make it look like part of the language by making it all lowercase, but it's still a little odd. Being able to 'using' a static class in would be perfect for this kind of stuff. To be used sparingly obviously.Expression bodied members, yes please! So pretty...
public double Dist => Sqrt(X * X + Y * Y);
Typecase and Guarded Cases would be lovely too. Basically anything that enables expression based coding in C#. It would be nice if the LINQ language functions were extended too: count, take, skip, tolist. It's slightly less pretty when having to wrap the expression in brackets to call .ToList();The `using` static is actually really good news. I have seen people who seem to be really mad about it, but sometimes it would be nice to have, for example:
// Something like Scala's 'Predef'
public static class Id<T>
{
public static Func<T, T> Identity { get { return x => x; } }
}
and then do: using Id;
var grouped = list.GroupBy(Identity);
Considering you can already open modules in F# (which are compiled down to static classes), it seems that feature found its way to C#. So maybe there is still hope for pattern matching and tuple support :)Equivalent of F#'s record types would be also awesome, which is what you put as 'readonly class':
type Person = { FirstName : string; LastName : string }
let single = { FirstName = "Jane"; LastName = "Doe" }
let married = { single with LastName = "Smith" }Perhaps C#'s record type could enforce immutability on not just the record but anything it's assigned to (maybe by using 'let'). That would allow the old mutable way to co-exist with language enforced immutability. It doesn't seem like it would clutter up or modify any existing code either, so if you don't like it, you never need to see it.
Not sure how that would work when assigning to a class's member property/field. Perhaps you opt out of immutability (of the reference) with a 'mutable' keyword:
class AClass
{
public mutable ARecordType Value;
}
Functional languages also 'extend' the behaviour of a type by defining functions that work with the type. But with an object-oriented language like C# you'd still expect the functionality to come with the type I think. So I suspect it would have to look something like this: type Vector
{
float X;
float Y;
float Z;
int Length => Math.Sqrt(X*X+Y*Y+Z*Z);
Vector Add( Vector value ) => new Vector { X+value.X,Y+value.Y,Z+value.Z };
}
So it turns the entire class into one big constructor (with everything public by default). All non-expression fields should be provided when you instantiate the object: let obj = new Vector { X=1, Y=2, X=3 };
I'd be very happy with that. Maybe I'll fork the compiler and have a go... if I can just find the time.... gahThere's no clear 'functional programming' benefit to the property syntax, either. Even though the syntax implies that Dist is logically some kind of a Func<double>, I still won't be able to write Func<double> f = Dist, because Dist is of type double.
I'm also concerned about the idea (only 'planned' for now, I believe) for the same syntax for methods which take arguments, though. That feels like it risks pushing developers into the pit of failure by encouraging them to write public methods that contain no parameter validation logic, just evaluation of a return value. It also means that the instant you want to add more complexity to a method you're forced to completely rewrite it in the conventional curly brace syntax.
Then there's the halfway world of using the syntax for a method which takes no arguments:
public double Dist() => Sqrt(X * X + Y * Y);
where now I can write Func<double> f = Dist...public double Dist => Sqrt(X * X + Y * Y);
> I'm also concerned about the idea (only 'planned' for now, I believe) for the same syntax for methods which take arguments, though.
Where's this? I must have missed it. Or could you show what it would look like?
public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);
Which is logically consistent with the property syntax, but as I say, I have my reservations about it.Yes it's enough if the property setting logic is only executed once during the lifetime of the object. So, it only works if they're supposed to be immutable.
Plus, public fields cannot be used for data binding.
Plus, you can't debug nor log whenever a field value is read.
Also, you can end up having to convert it into a property, and this involves various compatibility risks.
Meanwhile, there is no plausible scenario where you realize you must convert a property into a field.
What do you gain instead, with your design choice?
They are. Dig out some of the talks by Rich Hickey on immutability, he tends to put it pretty concisely, better than I ever could. But primarily it's about capturing snapshots of your world at a particular point in time so that you have a consistent view of the world. So all objects should be immutable.
http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hic...
> Plus, public fields cannot be used for data binding.
JsonConvert.SerializeObject()
JsonConvert.DeserializeObject()
That's all I need, or a .Select(). I don't use WinForms or any of the standard ASP.NET databinding stuff, it's ugly as sin. Even if I did, isn't there a LinqDataSource or something these days? Not sure if that would do the job, but I'd assume it would work with the results of a LINQ expression? Anyway, I don't really need that, and being able to reason about my code is more important.
> Plus, you can't debug nor log whenever a field value is read.
Never caused a problem, there's always the code that reads from it. Stick your breakpoint there. Also when you use immutable structures throughout, your bugs tend to not be in the 'values' (i.e. an immutable structure).
I tend to be breakpointing in the ctor if anything to check the setter logic or input values. Once the object is set, that's it. No need to keep checking.
> Also, you can end up having to convert it into a property, and this involves various compatibility risks.
Fields an properties are incompatible? How?
> What do you gain instead, with your design choice?
* I can pass an object to another method and know it's not going to change it without my permission.
* I don't have to analyse the inner workings of a class to find out how the state is going to be changed when I call a method on it.
* I can pass the same object to two threads running in parallel knowing that there won't be problems with the two threads writing to the same object..
* I can easily write transactional code and 'rollback' when it fails.
* I can write pure functions which makes it easier to test my code.
It's much easier to reason about a data structure if you know they won't change basically. There's huge advantages to that. Personally I find it makes my code more reliable and easier to compose and manage long term.
I agree it's not all sweetness and light using immutability with C#. There's more boilerplate than necessary and there's very little in the language to help the process.
Personally I think it's worth it, YMMV.
YMMV as you say, but I think that your needs are very specific if that's your base principle. Objects in C# are mutable by design, so you're kind of working against the language here. It sounds like your approach is closer to functional programming (but again, I don't know the context)
> I don't use WinForms or any of the standard ASP.NET databinding stuff
Neither WPF, Siverlight... long story short, hardly any popular .NET framework (nothing wrong about that, it just goes to show that your case is not mainstream)
> Fields an properties are incompatible? How?
See http://csharpindepth.com/articles/chapter8/propertiesmatter.... - "Compatibility issues".
> Never caused a problem, there's always the code that reads from it. Stick your breakpoint there
As long as it's only one or two places and as many breakpoints, sure :) life's beatiful then
> I can pass an object to another method and know it's not going to change it without my permission.
Achievable with properties (with private setter), so I wouldn't count it as a benefit.
I see where you're coming from, but to me you are pointing out the advantages of immutability, not choosing fields over properties. I think you are not wrong in preferring immutability, of course - I know it has its perks - but in assuming that one is synonymous with the other. Whereas you can implement immutability with properties just as well (and you can still use a readonly field as the backing field).
So it looks like:
var possibleInt = TryParse(s);
if(!possibleInt.Success)
{
//Fail out early
}
var actualInt= possibleInt.Data;
(Our Reply objects also allow for messages to be passed up, so that various layers can report details of the error they bumped into, and the presentation layer can then display them.)I guess that's why F# is starting to hit the prime time.
I posted an SO question about some of them, if anyone has any input on the matter: http://stackoverflow.com/questions/22881465/what-do-these-ne...
There were also some interesting discussions on the C# sub-reddit: http://www.reddit.com/r/csharp/comments/225g4b/microsoft_ope...
Hope that helps and answers some of the questions you have!
... so, in short, nothing definite yet, but the list above should be more or less accurate.
Microsoft usually does the license thing that takes away some of your rights. Is it the Apache2 license or something else? What are the limitations on this project?
Thanks in advance.