I was reading about the type safety in C# like how we can't assign an integer value to a bool etc., which made me to do some experiment.
I executed a code snippet hoping that it will give a compile time error but it worked and provider a result.
var add = 1 + "2"; // it gave 12 as result in C#
Please correct me if my understanding is incorrect and please share any document link explaining this in brief.
This compiles simply because there is a +
operator declared, that takes any object
as the first argument, and a string
as the second argument.
The langauage specification says:
The predefined addition operators are listed below. For numeric and enumeration types, the predefined addition operators compute the sum of the two operands. When one or both operands are of type
string
, the predefined addition operators concatenate the string representation of the operands.[...]
String concatenation:
string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);
These overloads of the binary
+
operator perform string concatenation. If an operand of string concatenation isnull
, an empty string is substituted. Otherwise, any non-string
operand is converted to its string representation by invoking the virtualToString
method inherited from type object. IfToString
returnsnull
, an empty string is substituted.
In your case, operator overload resolution would select the third overload in the above list. It is equivalent to 1.ToString() + "2"
.