Morale of a story: ~ is the right choice for concat operator

Dukc ajieskola at gmail.com
Fri May 25 08:27:30 UTC 2018


I was programming in C# and wanted to format an int in 
hexadecimal. It may be that I should have used some library 
function for that, but I decided to roll my own function for that 
anyway, in my general utility class:

public static string FormatHexadecimal(int what)
{   if (what == 0) return "0";
	string result = "";
	bool signed = what < 0;
	if (signed) what = -what;

	for (;what != 0;what >>= 4)
	{   int digit = what & 0x0000000F;
		result = (digit < 10? '0' + (char)digit: 'A' + (char)(digit - 
10)) + result;
	}

	return signed? "-" + result: result;
}

Looks correct, right? Yes.

But quess what? Op+ has a double meaning in C#, depending on 
context it means either addition or string concatenation. If you 
add two characters, it interprets it as a concatenation that 
results in a string with two charactes.  The correct way to do 
what I tried is:

public static string FormatHexadecimal(int what)
{   if (what == 0) return "0";
     string result = "";
     bool signed = what < 0;
     if (signed) what = -what;

     for (;what != 0;what >>= 4)
     {   int digit = what & 0x0000000F;
         result = (char)(digit < 10? (int)'0' + digit: (int)'A' + 
(digit - 10)) + result;
     }

     return signed? "-" + result: result;
}

You can imagine me confused when the first version returned way 
too long and incorrect strings. Now, if I were programming in D, 
this would not have happened. Using + always means an addition. 
If one wants to concatenate, ~ is used instead.

So, ~ may be a bit confusing for newcomers, but there is a solid 
reason why it's used instead of +, and it's because they have a 
fundamentally different meaning. Good work, whoever chose that 
meaning!


More information about the Digitalmars-d mailing list