Search code examples
c#stringoperator-overloadingchars

Why it's bad to provide an implicit operator of String(char[])?


We can:

var t=new String(new[] { '繁', '體', '中', '文' });

or

var encoding=Encoding.Unicode;
var bytes=encoding.GetBytes(new[] { 'E', 'n', 'g', 'l', 'i', 's', 'h' });
var t=encoding.GetString(bytes);

Without sometning like:

public static implicit operator String(char[] charArray) {
    return new String(charArray);
}

We cannot:

String t=new[] { 'р', 'у', 'с', 'с', 'к', 'и', 'й', '\x20', 'я', 'з', 'ы', 'к' };

I know that character array is not the same as a string; but sometimes I just want to assign a character array to a string directly; without explicit casting, converting or new X(new Y(new Z ....

And I think, personally, the reason it's not provided is possibly because:
The C-Sharp team wants the programmers, especially who have experience of C++/C to keep in mind that C-Sharp is NOT as similar as C++ or C.

The question is WHY not? Is that bad?


Solution

  • Implicit conversions are a compiler feature. There's nothing in the CLI spec that permits them, all conversions in IL are explicit. Even the simple ones like int to long and float to double. So it is up to the C# team in your case to make that syntax work.

    The way the C# team thinks about that is well published. Every possible feature starts at -100 points and needs some serious motivation to get to +100 to justify the work involved with designing the feature, implementing it, documenting it and maintaining it. I can't speak for them, but I seriously doubt this one makes it past 0. The alternative is obvious and simple so it just isn't worth it.