The problem originated from: There is an entity class with a string attribute, such
Class Demo
{
Public String STR { Get ; Set ;}
}
Demo d = New Demo ();
D. Str + = " XXXXX " ;
After instantiation, the STR attribute is added directly. I used to write this operation all the time. But one day I suddenly thought: After instantiating the demo object, the STR value is null. Why is there no error in addition?
So first find the explanation of addition in msdn:
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> + operators can be either unary or binary operators.
one dollar + operators are predefined for All numeric types. Perform one dollar for the value type + the result of the operation is the value of the operand.
predefines binary values for the numeric and string types + operator. For the value type, + calculate the sum of two operands. When one of the operands is a string or both are strings, + Concatenates the string representation of the operands.
the delegate type also provides binary + operator, which is used to concatenate multiple operators.
One dollar does not matter. Let's look at binary. The character string is preset with the + operator, which is actually called the string. the Concat method is used for addition. After decompiling, we can know that during the calculation, null is treated as a string. empty is a Null String, So adding the STR attribute directly does not cause an error.
When a string is added to other data types, the tostring () method of other data types is called to convert it into a string and then add it together.
Adding numeric values is relatively simple, but it is important to note that numeric values and null are added, and the result is null. In fact, 2 + null, the compiler will find the most matched + operator overload, so the int + Int ?, Here, the compiler treats null as Int ?, So we can add up. For the evidence, see:
The following is a comprehensive example:
1 + 1 + " X " = " 2x " ;
" X " + 1 + 1 = " X11 " ;
1 + Null + 1 + " X " = " X " ;
" X " + Null + 1 + 1 = " X11 " ;
Note: The addition operator is calculated from left to right.