Home >Backend Development >C++ >Why Does 'Cannot Modify Return Value' Occur with Auto-Implemented Properties in C#?

Why Does 'Cannot Modify Return Value' Occur with Auto-Implemented Properties in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-19 09:42:09913browse

Why Does

"Cannot modify return value" error in C#

When using auto-implemented properties, a "Cannot modify return value" error may occur, for example:

<code class="language-csharp">public Point Origin { get; set; }

Origin.X = 10; // 出现 CS1612 错误</code>

Error cause analysis

This error occurs because Point is a value type (structure). When accessing the Origin attribute, a copy of the value held in the class is returned, not the value itself. Modifying a copy's properties does not affect the original value.

Solution

To solve this problem, the underlying value needs to be modified directly. For value types, this can be achieved by storing a copy in a temporary variable and setting a property on that variable:

<code class="language-csharp">Point originCopy = Origin;
originCopy.X = 10;
Origin = originCopy;</code>

Alternatively, you can create your own backup field to store the value type and modify the field directly:

<code class="language-csharp">private Point _origin;
public Point Origin
{
    get { return _origin; }
    set { _origin = value; }
}</code>

In this way, you can directly modify the Origin attribute:

<code class="language-csharp">Origin.X = 10; // 此行现在可以正常工作,不会报错</code>

The above is the detailed content of Why Does 'Cannot Modify Return Value' Occur with Auto-Implemented Properties in C#?. 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