I was looking at the String and Int32 types through the reflector but couldn't find any operators that are defined.
If they aren't defined, how do +/-, etc works on these types?
I was looking at the String and Int32 types through the reflector but couldn't find any operators that are defined.
If they aren't defined, how do +/-, etc works on these types?
The String class has only two, they have CLS compliant names: op_Equality and op_Inequality. The compiler has lots of built-in knowledge of the System.String class. Necessary in order to be able to use the Ldstr opcode for one. Likewise, it translates the + operator into String.Concat().
Pretty much the story for Int32, there are direct matches between operators and IL opcodes.
The numeric operators are part of IL itself. The "+" operator on strings is a bit special though - it's not overloaded by the string type itself, it's done by the compiler. The C# compiler translates:
string x = a + "hello" + b;
into:
string x = string.Concat(a, "hello", b);
This is more efficient than if the concatenation had been done using normal operators, because otherwise a new string would have to be created at each concatenation.
Yes, these operations are translated to native IL instructions, not calling the "operator+" method explicitly. Its probably not managed code performing these actions...
The c# compiler is a crazy son of a b...I once tried to recreate the abilities of the Nullable type and was unable until in some comment on his blog Eric Lippert reassured me that its capabilities are also derived from what the compiler generates when it encounters nullable types.
The operators for primitives are a pain, as I found when trying to write generic support for operators (i.e. using T + T etc); there is also a discussion page here that covers this.
You can get around the issue by using abstractions such as Expression
(.NET 3.5) - otherwise, you'll have to look at raw IL, or use a handful of known methods.