Where are the operations defined for String, Int32, etc.?

I searched for String and Int32 types through a reflector, but could not find the operators that are defined.

If they are not defined, how +/- etc. work. for these types?

+6
string c #
source share
5 answers

Numeric operators are part of the IL itself. The "+" operator in strings is a bit special, although it is not overloaded with the type of string itself, it is executed by the compiler. C # compiler translates:

string x = a + "hello" + b; 

in

 string x = string.Concat(a, "hello", b); 

This is more efficient than if concatenation was performed using regular operators, because otherwise a new line would have to be created at each concatenation.

+10
source share

The String class has only two, they have CLS-compatible names: op_Equality and op_Inequality. The compiler has a lot of built-in knowledge about the System.String class. It is necessary to be able to use the Ldstr opcode for one. Similarly, it converts the + operator to String.Concat ().

Pretty much the story for Int32, there are direct matches between operators and IL opcodes.

+5
source share

Operators for primitives are a pain, as I discovered while trying to write general support for operators (i.e. using T + T, etc.) ,; The page that covers this is also discussed here.

You can work around the problem using abstractions such as Expression (.NET 3.5) - otherwise you will have to look for raw IL or use several well-known methods.

+2
source share

Yes, these operations translate into native IL instructions that do not explicitly call "operator +". Its probably not managed code that does these things ...

+1
source share

The C # compiler is the crazy son of b ... I once tried to recreate the Nullable capabilities and couldn't, until Eric Lippert reassured me in some comments on his blog that its capabilities also stem from what the compiler generates when it encounters types with zero value.

+1
source share

All Articles