There are two types of data in C #, one is value type data, the other is reference type data. Distinguishing between these two types of data while encoding can avoid some small coding errors.
First, let's say what types are value types, such as int, float, bool, and the types that are defined with struct, such as DateTime. In addition, such as String, arrays, and types defined with class are reference types. For C #, it is difficult to list all types for one by one respectively, which requires you to analyze and summarize in the coding process.
To better illustrate the difference between the two types, use the form below to illustrate.
  |
value type |
reference type |
memory allocation location |
allocated on stack |
allocated in the heap |
efficiency |
> High efficiency, no need to Address Translation |
low efficiency, needs to be translated |
|
|
|
Assignment operations |
|
|
function argument and return The value |
|
|
|
It is not easy to extend the |
easy to expand, easy to extend with type |
There is a clear concept of value types and reference types through a detailed comparison.
However, whether it is a value type or a reference type, it is an easy place to make mistakes as a function parameter or as a return value.
For a value type, when it is used as a function parameter, and you want to be modified in the function, the following operation cannot be modified.
public void Increment( int i )
{
i++;
}
To make real changes to the parameters that are passed in the function, you need to use the keyword ref, and the correct form is as follows.
public void Increment( ref int i )
{
i++;
}
That is, if you need to modify a value type parameter in a function, you need to identify it with ref or out to actually implement it.
For a reference type, when it is a function parameter, it encounters exactly the opposite of the value type, that is, it does not want to be modified in the function, for example.
public void AddValue( MyType typValue )
{
typValue.Count = typValue.Count + 15;
}