Roslyn: Init char array with a prefixed string literal

Created on 21 Nov 2016  路  5Comments  路  Source: dotnet/roslyn

You may have written or come across something like this:
char[] foo = "abcdefg".ToCharArray();

char arrays can be kind of painful to type:
char[] bar = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'};

Suggestion: suffixing prefixing a "c" to a string literal will be equivalent to an array of chars.

Example:
char[] abcdefg = c"abcdefg";
Becomes equivalent to:
char[] abcdefg = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'};

You can omit the suffix prefix or use an "s" if you want a string, similar to how doubles work (e.g. 1.0 and 1.0d)

EDIT: prefix looks like it would be better than a suffix

Area-Language Design

All 5 comments

Also, I would like to propose a implicit operator for converting a char-array to a string, so that

char[] my_array = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
string s = new string(my_array);

would become

string s = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };

@Unknown6656 what about the other way around?

You could define an implicit conversion to char[] via "extension everything" (#11159).

I know it isn't about the syntax but the idea, however, I think that having a prefix is much better than having a suffix for strings because it can be a lengthy string so for readability it should be char[] abcdefg = c"abcdefg";

@eyalsk Agreed, that's originally what I considered - I thought a suffix would be more consistent with numeric literals (1.0d, 1.0f, 1.0m, 1L, ... ). However, I suppose there's already other string literal prefixes (@, $) so maybe a prefix is the way to go.

Was this page helpful?
0 / 5 - 0 ratings