Home >Backend Development >C++ >C# `ref` vs. `out`: When to Use Which Keyword?

C# `ref` vs. `out`: When to Use Which Keyword?

Barbara Streisand
Barbara StreisandOriginal
2025-01-24 12:08:10320browse

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:

  • The caller must initialize the object before passing it to the method.
  • Methods can access objects in both directions and modify their state.
  • Any changes made within a method will be reflected in the caller's context.

out:

  • The caller does not need to initialize the object before calling the method.
  • Method initializes the object inside its body.
  • Methods can only access objects in one direction and can assign values ​​to them.
  • After the method is called, the caller will receive the initialized object.

Which keyword to choose:

Choose ref:

  • The object is initialized before the method is called and needs to be modified.
  • The original state of the object is important to the caller.

Choose out:

  • Objects do not need to be initialized before method calls.
  • Method should create a new object and return it.
  • The original state of the object is not required by the caller.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn