Had a coworker ask me this, and in my brain befuddled state I didn’t have an answer:
Why is it that you can do:
string ham = 'ham ' + 4;
But not:
string ham = 4;
If there’s an implicit cast/operation for string conversion when you are concatenating, why not the same when assigning it as a string? (Without doing some operator overloading, of course)
When concatenating the compiler turns the statement
'ham' + 4into a call toString.Concat, which takes twoobjectparameters, so the value4is boxed and thenToStringis called on that.For the assignment there is no implicit conversion from
inttostring, and thus you cannot assign4to astringwithout explicitly converting it.In other words the two assignments are handled very differently by the compiler, despite the fact that they look very similar in C#.