Home >Backend Development >C++ >C# `ref` vs. `out`: When to Use Which Keyword?
Differences and application scenarios of ref
and out
keywords in C#
In C#, the ref
and out
keywords are used to pass objects by reference to methods or functions. They allow the caller to manipulate the object directly within the called method.
Usage scenarios:
ref
and out
both allow modification of the object passed to the method. The key difference is their initialization requirements:
ref
:
out
:
Which keyword to choose:
Choose ref
:
Choose out
:
Example:
Consider the following method of modifying the MyClass
property of a Count
object:
<code class="language-csharp">public void IncrementCount(ref MyClass myClass) { myClass.Count++; }</code>
Passing a pre-initialized myClass
object to this method will cause its Count
properties to be modified. On the other hand, passing an empty or uninitialized object will result in a runtime error.
Use out
in this scene:
<code class="language-csharp">public void CreateNewClass(out MyClass myClass) { myClass = new MyClass(); }</code>
In this case, the method creates and assigns a new myClass
instance to the MyClass
parameter. The new object is returned to the caller, which has an initialized object in its local context.
The above is the detailed content of C# `ref` vs. `out`: When to Use Which Keyword?. For more information, please follow other related articles on the PHP Chinese website!