Collection Literals and Constructor Parameters #7622
Replies: 5 comments 24 replies
-
Doesn't seem to be much of a difference using existing syntax with target-typed new: Test(new(StringComparer. InvariantCulture) { "a", "b", "c"} ); |
Beta Was this translation helpful? Give feedback.
-
If we were talking only about collection expressions, I would be against this idea, but if it could be used for string interpolation culture propagation, etc., it might be a little more appealing. |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
Why not just enable collection literal in the position of initializer? Test(new(StringComparer.InvariantCulture) [ "a", "b", "c" ] ); |
Beta Was this translation helpful? Give feedback.
-
Another alternative that might work is pass the arguments to the constructor as part of the collection expression itself so something like this:
I'm not sure whether it's confusing so maybe something like this:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi C# team:
I use HashSet and dictionaries s a lot in my code and would love to be able to use them with collection literals. They work great when I don't need an
IComparer<T>
but once I do, I can't use them.I want to throw out an idea on how IComparers could be used.
Allow calls with a syntax like one of the following:
Option 1:
Test(["1", "2", "3"] with { comparer = StringComparer.InvariantCulture, });
Option 2:
Test(using { comparer = StringComparer.InvariantCulture} ["1", "2", "3"]);
Option 3:
Test(with { comparer = StringComparer.InvariantCulture} ["1", "2", "3"]);
(Option 3 is my preference)
In the code above,
with/using
means "When selecting the constructor for the specified collection literal, the constructor that is selected by the compiler must have a parameter namedcomparer
which is compatible with the value provided. In the event that multiple constructors meet all of the specified criteria, the compiler is free to pick any of the available constructors." The syntax would essentially be like partially specifying a PowerShellargset
. Also, while I might only be specifying thecomparer
argument, any number of constructor parameters could be specified.Beta Was this translation helpful? Give feedback.
All reactions