The C reference type is analyzed as a parameter for a method

  • 2020-11-25 07:30:15
  • OfStack

An example of this article examines the C# reference type as an argument to a method. Share to everybody for everybody reference. The details are as follows:

In c# or java, parameter passing is the value of the passed parameter itself,

For a value type, the value itself is passed.

For reference types, when defining reference type variables, one is a variable in the stack and one is stored as a pointer to the address of the object instance allocated in the heap, except for the null value if the object is not instantiated.

When you pass a reference type variable, you also pass a value,

But its value is the memory address, which specifies the object in the heap.

So when we change the contents of an object in a method, the objects that our peripheral reference type variables operate on also change, because they point to the same one.

But if we instantiate a new object in the method of the operation, a new object will be created in the heap, which will be two different objects. At the end of the operation, if the object is not specially handled, there will be no variables pointing 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 occurs when an object is called with an empty reference.

The reason is that the object is initialized in the method, but the peripheral sb and the method sb are two different variables, and the peripheral sb still specifies null after the object instance is allocated in the method.

If you want to undo this exception, there are several ways. The first is to initialize the object effectively, without setting it to null, if you can just use new StringBuilder(). Do not re-instantiate within a method. The second is if an object cannot be initialized on the periphery, like an interface object, and needs to be deferred to a method for initialization, either by returning a value or by using the method of the ref parameter.

Such as:

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;
}

Hopefully this article has helped you with your C# programming.


Related articles: