C # When the reference type is used as a method parameter
In c # (java), parameter passing is the value of the passed parameter. For the value type, the value itself is passed. For reference types, when defining reference type variables, one is the variables in the stack, storing a pointer pointing to the address of the object instance allocated in the heap, of course, if the object is not instantiated, the exception is returned when null is given. When a reference type variable is passed, the value is also passed, but its value is the memory address, which specifies the object in the heap. So when we change the object content in the method, the object for the reference type variable operation on our periphery also changes, because they point to the same one. However, if we instantiate the object in the operation method, a new object will be generated in the heap, which is two different objects than the original one, at the end of the operation method, if this object is not specially processed, no variable points to it and it will be destroyed. Example: new Thread () =>{ try {StringBuilder sb = null; // addline (ref sb); addline (sb); rtb_log.InvokeIfRequired () => rtb_log.AppendText (sb. toString () + "\ r \ n");} catch (Exception ex) {rtb_log.InvokeIfRequired () => rtb_log.AppendText (ex. message + "\ r \ n");} finally {if (conn! = Null & conn. state = ConnectionState. open) conn. close ();}}). start (); void addline (StringBuilder sb) {if (sb = null) sb = new StringBuilder (); sb. append ("hello world! ");} An exception occurred when calling an empty object reference. The reason is that the object is initialized in the method, but the sb in the peripheral and the sb in the method are two different variables. After the object instance is allocated in the method, the peripheral sb is still null. to remove this exception, there are several methods. The first method is to initialize the object effectively. Do not set it to null. If so, you can directly use new StringBuilder (). Do not instantiate a method. Second, if the object cannot be initialized on the periphery, such as the interface object, it needs to be delayed to initialize In the method, you can use the return value method or the ref parameter method. Example: void addline (ref StringBuilder sbx) {if (sbx = null) sbx = new StringBuilder (); sbx. Append ("hello world! ");} Or StringBuilder addline2 (StringBuilder sbx) {if (sbx = null) sbx = new StringBuilder (); sbx. Append (" hello world! "); Return sbx ;}