dotnet / dotnet/runtime

[API Proposal]: Object.MemberwiseClone should be `unsafe` in unsafe v2

Open
#132,533 12 comments 1 reaction 0 assignees View on GitHub
api-suggestion area-System.Runtime reduce-unsafe
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

`MemberwiseClone` allows any derived type to break any implicit ownership assumptions for any fields. For example, assumptions that a particular `SafeHandle` or `GCHandle` is owned by a particular object can be trivially broken by `MemberwiseClone`. If these fields are `private` or `internal`, the contract can even be invisible to implementing types, making it difficult to document as `unsafe` on a particular class.

We should

### API Proposal

```diff
namespace System;

class Object
{
- protected object MemberwiseClone();
+ /// Copies internal state that may expect a single owner. Callers must ensure that their class hierarchy has no members that expect single ownership.
+ protected unsafe object MemberwiseClone();
}
```

### API Usage

```csharp

public class MyClonableType
{
public MyClonableType Clone()
{
// safety: MyClonableType has no members that expect a single owner.
unsafe
{
return (MyClonableType)MemberwiseClone();
}
}
}
```

### Alternative Designs

_No response_

### Risks

_No response_

Contributor guide

Open the contributing guide

Research direction

The proposal targets System.Object.MemberwiseClone; start by reviewing the API proposal and its safety comment. Done means deciding whether the protected method should be marked unsafe and documenting the caller safety contract, with the C# usage example as the expected behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
api, backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.