Skip to content

[API Proposal]: change GCHandle<T>.ToIntPtr to be an instance method #115053

Closed as not planned
@paulbartrum

Description

@paulbartrum

Background and motivation

I am interoping with unmanaged code a lot and so GCHandles are very useful. I was testing out the new GCHandle class, which is new in.NET 10 (see #94134). In general it's a big improvement, but I'd like to suggest a small change to ToIntPtr(), which is currently a static method and so unnecessarily requires writing the full type name, including the generic parameter type. This can be made less verbose by changing the method to be an instance method (see API usage).

API Proposal

public class GCHandle<T>
{
    // Was: public static IntPtr ToIntPtr(GCHandle<T> value);
    public IntPtr ToIntPtr();
}

public class PinnedGCHandle<T>
{
    // Was: public static IntPtr ToIntPtr(PinnedGCHandle<T> value);
    public IntPtr ToIntPtr();
}

public class WeakGCHandle<T>
{
    // Was: public static IntPtr ToIntPtr(WeakGCHandle<T> value);
    public IntPtr ToIntPtr();
}

API Usage

// Before:
var handle = GCHandle<MyClass>.ToIntPtr(new GCHandle<MyClass>(myClassRef));

// After:
var handle = new GCHandle<MyClass>(myClassRef).ToIntPtr();

Alternative Designs

Leave as is.

Risks

The change is not backwards compatible, but since the API has not been released outside of a preview, I believe the team considers this kind of break acceptable.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions