This is super dumb, but I’ve googled and checked references and I just cannot find an answer… Why can an int or float etc be added as part of a string without converstion but not on it’s own? that is:
while this work fine:
string st = "" + 12;
this doesn’t (of course):
string st = 12;
Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?
In the first statement, the left operand for the
+is a string, and as such+becomes the concatenation operator. The compiler finds the overload for that operator which takes a string and an arbitrary value as operands. This converts both operands to strings (usingToString()) then joins them.The second statement does not work because there’s no implicit cast from
inttostring.You can control how the conversion is done by using parentheses to change the order of operations (semi-effective) or by writing code to handle the conversions pre-emptively.