Skip to content

[bgen] Add support for generating nullable factory methods from failable ObjC initializers #26167

Closed

Description

@rolfbjarne

Background

Several Apple frameworks expose failable Objective-C initializers — init* methods that can return nil on failure. In C# we expose these as static nullable factory methods (e.g. Create) rather than constructors, since C# constructors can't return null.

Currently, every such case requires manually writing the same boilerplate in a partial class file:

// src/FSKit/FSEntityIdentifier.cs
[SupportedOSPlatform ("macos27.0")]
public static FSEntityIdentifier? Create (NSUuid uuid, NSData qualifierData)
{
    if (uuid is null)
        ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (uuid));
    if (qualifierData is null)
        ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (qualifierData));

    var rv = new FSEntityIdentifier (NSObjectFlag.Empty);
    rv.InitializeHandle (rv._InitWithUuidQualifierData (uuid, qualifierData), "initWithUUID:qualifierData:", false);
    if (rv.Handle == NativeHandle.Zero) {
        rv.Dispose ();
        return null;
    }
    return rv;
}

This same pattern appears in at least:

  • src/FSKit/FSEntityIdentifier.cs
  • src/WebKit/WKWebExtensionMatchPattern.cs
  • src/AVKit/AVCaptureEventSound.cs
  • src/SensitiveContentAnalysis/SCVideoStreamAnalyzer.cs
  • src/ScreenTime/STWebHistory.cs
  • src/AudioUnit/AUHeadTrackingBinauralRenderer.cs
  • src/Foundation/NSAttributedString.cs
  • src/AVFoundation/AVAudioRecorder.cs
  • src/AVFoundation/AVAudioPlayer.cs

Proposal

Add a bgen attribute (or extend an existing one) so that the API definition file can declare this intent, and bgen generates the boilerplate automatically.

Option A — [FactoryMethod] attribute on the binding constructor:

[Export ("initWithUUID:qualifierData:")]
[FactoryMethod ("Create")]
NativeHandle Constructor (NSUuid uuid, NSData qualifierData);

bgen would:

  1. Suppress generation of the public C# constructor for that selector.
  2. Instead generate a public static T? Create (...) method with the same parameters plus null-guard checks, calling InitializeHandle (..., allowNullHandle: false) and returning null when the handle is zero.

Option B — Rename the binding method from Constructor to match the desired factory name:

[Export ("initWithUUID:qualifierData:")]
NativeHandle Create (NSUuid uuid, NSData qualifierData);

bgen could detect that a method named differently from Constructor but whose selector starts with init is a failable initializer, and generate the static nullable factory.

Open questions:

  • Should the attribute carry the factory method name, or should bgen derive it from the managed method name?
  • Is there an existing attribute ([Constructor]) we could reuse or extend?
  • Not all init* selectors are failable — we need a way to distinguish which ones can return nil. The attribute approach is more explicit.
  • Should the generated factory method respect platform availability attributes (e.g. [SupportedOSPlatform])?

References

Activity

  1. rolfbjarne commented on Jul 17, 2026

    @rolfbjarne
    MemberAuthor

    This is interesting, the original manual code that made me ask Copilot to file this issue was not because it was a failable ObjC initializer, but because there was already another C# constructor with the same managed signature (and thus a factory method was needed). Somehow Copilot reasoned incorrectly and came up with the other correct answer.

    Anyways, both reasons are valid reasons for needing a factory method.

    FWIW I'm leaning towards option A ([FactoryMethod]) - being explicit makes the api definition easier to read.

  2. added
    request-for-comments
    generator
    feature
    on Jul 17, 2026
  3. added this to the Future milestone on Jul 17, 2026
  4. dalexsoto commented on Jul 17, 2026

    @dalexsoto
    Member

    @rolfbjarne yeah agreed +1 on the option A [FactoryMethod] I like that it is explicit

  5. removed
    request-for-comments
    on Jul 20, 2026
  6. added a commit that references this issue on Jul 30, 2026
    36b951f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featuregenerator

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions