Basicly I see one benefit in here, and I do not belive that it is a bad design decision. Internally characters are integer numbers, either. The conversion between a number and an character, based on equivalence tables is called encoding.
However in .NET characters and strings are unicode encoded. The first 128 characters in unicode are equal to the former ASCII encoding.
If you want to convert a string into a number (or back) this can be done pretty easy when you assume that characters are also numbers. Imagine something like this:
char c = '1';
int i = Convert.ToInt32(c);
The offset between numerical characters and numerical representation is allways 0x30. Internally it is now possible to write something like this:
int result = c - 0x30;
if (result < 0 || result > 9)
throw new InvalidCastException();
Note that the example works for characters since 1 character can only hold 1 numerical literal (0 to 9). For strings you also need to multiply the index of the character with 10 and the result and add it to the overall result value.
Of course this is much like it works "under the hood". But for practice it is bad design to use the operator+
(or minus) for strings or characters. This also has another reason. Imagine the following code:
string s1 = "Hello";
string s2 = " ";
string s3 = "World";
string helloWorld = s1 + s2 + s3;
When calling the operator+
the following is happening:
- Allocate memory for the length of string 1 plus the length of string 2.
- Copy string one to the front of the newly allocated array.
- Copy string two to the back of the newly allocated array.
- Return the new string's instance.
This will happen two times, so you will have a temporary string instance, stressing the garbage collector. Since this example is pretty simple it might not be much, but I also found strings like this many code samples:
string sql = "SELECT " + c1 + ", " + c2 +
" FROM " + table +
" WHERE " + c1 + " = " + condition + ";";
Maybe the compiler will optimize this code, but you cannot rely on him. In this case I would prefer a wrapper to StringBuilder
, or at least String.Format
that internally uses the StringBuilder
.
To come to a conclusion:
Implicit conversion from characters to integers are usefull to simplify encoding, but you should not use plus or minus operators when it come's to build up strings or characters.