[Syntax Deficiency] C# syntax does not accept Span<char> or ReadOnlySpan<char> as valid values with ToString() methods #1758
-
This becomes a bit problematic when writing code with for instance interpolated strings and passing to them Console.WriteLine($"My message with span {new Span(new char['m', 'e', 's', 's', 'a', 'g', 'e' ])} is failing to compile");
// Error CS0029 Cannot implicitly convert type 'System.ReadOnlySpan<char>' to 'object' IMHO we should support calling |
Beta Was this translation helpful? Give feedback.
Replies: 8 comments
-
using System;
class Program
{
static void Main()
{
Span<char> s = stackalloc[] { 'm', 'e', 's', 's', 'a', 'g', 'e' };
// OK. Invoking ToString.
Console.WriteLine($"{s.ToString()}"); // message
// NG. Boxing to object.
Console.WriteLine($"{s}");
}
} |
Beta Was this translation helpful? Give feedback.
-
@ufcpp I know you can invoke |
Beta Was this translation helpful? Give feedback.
-
How would this work with FormattableString fs = $"{42}";
Console.WriteLine(fs.GetArgument(0) is int); But that only works because |
Beta Was this translation helpful? Give feedback.
-
String interpolation doesn't call |
Beta Was this translation helpful? Give feedback.
-
@HaloFour Thanks for explanation but unfortunately it is not an option due to additional allocations. My expectation would be that C# would support it and if necessary runtime would provide support as well. Otherwise we have a lot work done for implementing |
Beta Was this translation helpful? Give feedback.
-
String interpolation does a lot of additional allocations which you cannot avoid. That's true if you pass any value, including bog-standard structs, which have to be boxed first.
The "rough edges" are intentional limitations to keep your use of those types on very tight "safe" rails. There's a great deal you're not allowed to do with a |
Beta Was this translation helpful? Give feedback.
-
I will note that it's been considered that the C# compiler emit different code when interpolating string literals/constants as to not incur the cost of composite formatting, which includes boxing. Maybe the same could be done with |
Beta Was this translation helpful? Give feedback.
-
Yeah, you are most probably right, however, it would be significant perf improvement if we would use internally spans to interpolate strings. Anyway format string can be represented as span and sliced to include spans. This would require only one allocation of the new return string in the form of writable |
Beta Was this translation helpful? Give feedback.
@4creators
String interpolation doesn't call
ToString
, it passes the argument to an API that expectsobject
. What that API happens to do with the argument is completely opaque and subject to formatters and the like. To have C# explicitly callToString
forSpan<T>
or otherref
structs would change the expectation of what that feature does. You can work around this today by callingToString
yourself.