Skip to content

Avoid defensive copies – outdated example (in C# 10+ there are no _defensive copies_) #27175

@deep-outcome

Description

@deep-outcome

In chapter Avoid defensive copies there is

The Point3D structure is not a read-only struct. There are six different property access calls in the body of this method. On first examination, you may think these accesses are safe. After all, a get accessor shouldn't modify the state of the object. But there's no language rule that enforces that. It's only a common convention. Any type could implement a get accessor that modified the internal state.

private static double CalculateDistance(in Point3D point1, in Point3D point2)
{
    double xDifference = point1.X - point2.X;
    double yDifference = point1.Y - point2.Y;
    double zDifference = point1.Z - point2.Z;

    return Math.Sqrt(xDifference * xDifference + yDifference * yDifference + zDifference * zDifference);
}

Next paragraph starts with note abote readonly modifier

Without some language guarantee, the compiler must create a temporary copy of the argument before calling any member not marked with the readonly modifier.

Because this example does not show exact implementation of Point3D chapter maybe could be enriched with [!NOTE] about C# 8+ autogenerated readonly modifiers for autoimplemented-property getters.


Excerpts from chapter Declare readonly members for mutable structs

If you use auto-implemented properties, the compiler adds the readonly modifier to the get accessor for read-write properties.

The compiler adds the readonly modifier to the auto-implemented property declarations for properties with only a get accessor.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.


Associated WorkItem - 54740

Metadata

Metadata

Assignees

Labels

📌 seQUESTeredIdentifies that an issue has been imported into Quest.advanced-concepts/subsvcdotnet-csharp/svcokr-qualityContent-quality KR: Concerns article defects (bugs), freshness, or build warnings.

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions