Home >Backend Development >C++ >What's the Difference Between C#'s `ref` and `out` Keywords for Modifying Objects?

What's the Difference Between C#'s `ref` and `out` Keywords for Modifying Objects?

Susan Sarandon
Susan SarandonOriginal
2025-01-24 12:01:09458browse

What's the Difference Between C#'s `ref` and `out` Keywords for Modifying Objects?

C# ref and out Keywords: A Clear Distinction

In C#, when methods need to modify objects passed as arguments, the ref and out keywords play crucial roles. While both enable modifications, their behavior differs significantly.

ref Keyword: Modifying Existing Objects

The ref keyword signifies that the method operates directly on the original object passed as an argument, not a copy. Any changes within the method directly affect the original object. Importantly, the object must be initialized before being passed to the method.

out Keyword: Creating and Returning Objects

Conversely, the out keyword indicates that the method is responsible for initializing the object. The method assigns a value to the object, and this newly initialized object is then returned to the caller. out parameters are declared but do not require initialization before the method call.

Choosing the Right Keyword

The choice between ref and out depends on the method's purpose:

  • Use ref to modify an existing object; the method doesn't create a new object.
  • Use out to create and return a new object; the method is responsible for initialization.

Illustrative Examples:

<code class="language-csharp">public void ModifyWithRef(ref MyClass someClass)
{
    someClass.Property1 = 10;
}

public void CreateWithOut(out MyClass someClass)
{
    someClass = new MyClass { Property1 = 20 };
}</code>

ModifyWithRef modifies an existing someClass using ref. CreateWithOut creates and initializes someClass using out. Note the initialization requirement difference when calling these methods.

The above is the detailed content of What's the Difference Between C#'s `ref` and `out` Keywords for Modifying Objects?. 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