Skip to content

[API Proposal]: GCHandle.GetTargetUnsafe() with no handle validation #94113

Closed as not planned
@Sergio0694

Description

Background and motivation

GCHandle is often used in scenarios (such as handwritten COM objects, or other interop setups) where callers have complete control over the handles, and nobody else is ever mutating them. The only way, currently, to get a target, is to use GCHandle.Target, which always incurs in a validation check, which is pretty much always just useless branching in these cases.

This proposal is about adding a way to get the handle target with no branches, when callers know no validation is needed.

API Proposal

namespace System.Runtime.InteropServices;

public struct GCHandle
{
+   public readonly object? GetTargetUnsafe();
}

API Usage

// In a constructor (or wherever)
this.handle = GCHandle.Alloc(myObj);

// Later on
object? target = this.handle.GetTargetUnsafe();

Alternative Designs

Alternatively (as @tannergooding also suggested), we could instead just remove the validation check from GCHandle.Target. This would technically be a breaking change, as it would cause invalid handles to throw a NullReferenceException instead of an InvalidOperationException, but it might be considered acceptable in this scenario, since it's a niche API.

The benefit of this approach is that no new API is needed, and everyone "gets faster for free".

Risks

With the new API, no risk.
With the alternate design, people taking a hard dependency on that exception type would break.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    • Status

      No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions