Comments (20)
I'd go with something like this:
$i"count: {count}"
$c"count: {count}"
The reason is the string can be lengthy and it might be annoying to look for, some people might miss it so for readability I'd go with a prefix and not postfix. :)
from csharplang.
How about using this syntax instead:
$("count: {count}", CultureInfo.InvariantCulture)
Where the second "argument" is an IFormatProvider.
from csharplang.
With this syntax you would not need to add the "static using" in every file. And you can easily put it in one of the other IFormatProviders. It's not smaller but I don't think the goal of interpolated strings is to make it smaller. It was added so you can just put your arguments at the place where you use it instead of worrying about the order of your arguments when you do a string.Format. And with my syntax you can easily add the CultureInfo when you need it.
from csharplang.
This was addressed in C# 10 with interpolated string handlers: string.Create(CultureInfo.InvariantCulture, $"{somevalue} is formatted with invariant culture")
will do this.
from csharplang.
The problem with i
suffix is that it may conflict with complex numbers, if a later version of C# will include literals for them like 5+2i
...
However, I completely agree that the amount of code to use invariant culture is a bit too big. In case of interpolated strings, "using static" (using static System.FormattableString
+ Invariant("{foo}")
) helps somewhat, but there're lots of other cases where it's much more complex. There's nothing in the framework to simplify string.Compare(s1, s2, true, CultureInfo.InvariantCulture)
and numerous other methods, and suffixes for just string interpolation won't help much. π
from csharplang.
See also dotnet/roslyn#12298
from csharplang.
Just for interpolated strings, I'd propose an alternate prefix. Perhaps $$
instead of $
.
(This however doesn't solve the problem of having to specify InvariantCulture
in many other places, so if someone finds a more general solution, it should be preferred.)
from csharplang.
Complex numbers are digits only (and + and i), so there will be no conflict with strings that are marked with double quotes.
Other cases you mention are just method calls, it's out of the scope of this topic, that is the extension to interpolated strings syntax.
from csharplang.
String interpolation is so convenient I see people use it everywhere, even for $"x = {x}"
kind of code. So yay for the C# feature but most dev don't realize:
- The current culture is used, so the many usages to format HTML, SQL, XML, JSON, URL, culture-neutral logs and co. are often dubious;
- Interpolation is a lot more heavy than doing
"x = " + x
. It is boxing, allocating and always formatting (even for strings).
With the right using
you can indeed do Invariant($"x = {x}")
which in my opinion helps already a lot. But very few people seem to even know that an interpolation can be IFormattable
, or the existence of the Invariant()
helper.
- It is hard to discover / little known by the dev community.
- It is still verbose if you write mainly code that produces machine-strings (as opposed to user-facing).
- It doesn't improve perf.
Although I don't like the suffix proposal, I would love to see a shorthand for Invariant($"x = {x}")
. Because:
- More people would learn about the new language feature (and use it).
- It will be much shorter / nicer.
- C# could produce optimal code that creates the string without boxing, allocating or formatting when it's not necessary.
As for the syntax, I think it's better if we keep everything at the same place, i.e. at the start. Maybe $i"x"
? It becomes a bit hieroglyphic with verbatim, though: $i@"x..."
. Or alternative symbol %"x"
?
EDIT: I think the $$"x"
proposal is not so bad. If there's no better suggestion I'd π
from csharplang.
@dlemstra How is it better than the current Invariant($"count: {count}")
?
from csharplang.
It's counter-intuitive. Indeed it looks like error in source file.
$"count: {count}"c // this will call string.Format with CultureInfo.CurrentCulture
$"count: {count}"i // this will call string.Format with CultureInfo.InvariantCulture
$"count: {count}" // as it is now, this will call string.Format without CultureInfo, effectively (...)
This approach is much better and understandable from the first sight:
$("count: {count}", CultureInfo.InvariantCulture)
from csharplang.
@Opiumtm adding dollar sign before the double-quote for interpolated string is also counter-intuitive if you look from the perspective of C# 5 :)
from csharplang.
@eyalsk π
from csharplang.
@dlemstra How is it better than the current
Invariant($"count: {count}")
?
Different in two aspects. First, FormattableString.Invariant
needs underlying FormattableString
instance, hence we need to allocate FormattableString
on heap and this is won't fix see dotnet/roslyn#15395 - closed by @gafter.
This could be avoided if FormattableString
was a struct proposed in dotnet/roslyn#518 - dismissed by @gafter after providing good argumentation.
Nevertheless, with the proposed new syntax, if $"..."
is just a syntactic sugar for string.Format(...)
then I would expect $$"..."
or $("...", CultureInfo.InvariantCulture)
to be just a sugar for string.Format(CultureInfo.InvariantCulture, ...)
(or actually any culture), hence no need for intermediate FormattableString
instance.
Second, the necessity of putting using static System.FormattableString
and Invariant(
in the front of your text if you intend to use string interpolation for logging or exception messages really reduces readability of the code without a good reason.
Altogether, this may look like a discussion about some petty syntax addition, but I believe we have inherent problem with interpolated strings that not that petty.
@gafter I would really appreciate if you could take a stance here, since you were involved the other issues related to string interpolation that are now closed, but no improvement was made so far. Does C#/Roslyn team plan to provide us some workaround at least for allocation issue related to the use of Invariant(
?
from csharplang.
@nanoant I haven't heard any proposals that fit the bill. If it is a change of language you're looking for, this belongs in the csharplang
repo.
from csharplang.
dup #177
from csharplang.
Perhaps a syntax like below could be used in that it would use the one set right after $, and let any of the placeholder override the default per needs?
This would align with the current overall syntax and enable in-string flexibility?
$:en-US"?latitude={lat:F4}&longitude={lon:F4}&amount={amount:C:da-DK}"
$:env"?latitude={lat:F4:invariant}&longitude={lon:F4:invariant}&amount={amount:C}"
from csharplang.
Not quite the same kind of flexibility and syntactic sugar though...
from csharplang.
This was addressed in C# 10 with interpolated string handlers:
string.Create(CultureInfo.InvariantCulture, $"{somevalue} is formatted with invariant culture")
will do this.
Meh, this doesn't address much as we already have a shorter version FormattableString.Invariant($"count: {count}")
.
from csharplang.
It is more painful to lose CultureInfo in nested interpolation rather than the length of the code.
#6882
from csharplang.
Related Issues (20)
- More user-friendly Compile-time type checking / ζ΄ε δΊΊζ§εηηΌθ―ζΆη±»εζ£ζ₯ HOT 2
- Feature Request: Syntax Sugar for AddRange in List Initialization
- [Proposal]: request support for the ISO 8601 standard 24:00:00 time format in C# HOT 2
- C#: foreach breaking when the IEnumerator.MoveNext method throws exceptions HOT 2
- [Proposal]: Dictionary expressions HOT 48
- strong typed CallerAttributes like CallerMemberName CallerArgumentExpression HOT 2
- CS8509 - Consider Exhaustiveness For Algebraic Data Types HOT 17
- [Proposal]: Implementation specific documentation HOT 2
- [Proposal]: First-Class Span Types HOT 30
- [Proposal]: Collection Expressions Next (C#13 and beyond) HOT 46
- Open issues: Breaking changes HOT 27
- [Proposal]: Field and value as contextual keywords HOT 33
- [Proposal]: Extended identifier syntax
- [API Proposal]: IsNullableAttribute to flow nullability of generic type parameters into methods HOT 4
- Anonymous type optimization HOT 5
- Feature Request: Recursively Foreach
- Compiler can't determine best common type for `switch` expression HOT 8
- [Proposal]: Relax `Add` requirement for collection expression conversions to types implementing `IEnumerable` HOT 2
- [Proposal]: Proposal for Allowing Single-Element Tuples in Type Definitions HOT 2
- [Proposal]: Params collections and older language versions
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. πππ
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from csharplang.