Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

.net

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?

like image 383
Joan Venge Avatar asked Jan 28 '09 21:01

Joan Venge


2 Answers

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.

like image 32
Hans Passant Avatar answered Oct 21 '22 03:10

Hans Passant


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.

like image 111
Jon Skeet Avatar answered Oct 21 '22 03:10

Jon Skeet