One of major feature of the Monobjc bridge is the ability to expose .NET class containing extension methods to the Objective-C runtime: on the .NET side, the class is like any other .NET class containing extension methods and on the Objective-C side, the class is seen like any other Objective-C category. The Monobjc bridge provides a fine grained control on how a .NET extension methods should be exposed in the Objective-C.

Rules to follow

The following rules apply when exposing a .NET category to Objective-C runtime:

  • The .NET class MUST be public.
  • The .NET class MUST be static.
  • The .NET class MUST exposed public static extensions methods. The static extensions methods are mapped to Objective-C class messages with a public scope.

The following code shows a .NET class containing extension methods exposed to Objective-C runtime:

using System;
using Monobjc.AppKit;
using Monobjc.Foundation;

namespace Monobjc.Samples.AppList
{
    [ObjectiveCCategory("NSRunningApplication")] // (1)
    public static class NSRunningApplication_BooleanPropertiesAsStrings // (2)
    {
        [ObjectiveCMessage("activeString")] // (3)
        public static NSString ActiveString(this NSRunningApplication runningApplication) // (4)
        {
            return runningApplication.IsActive ? "Of Course" : "Not At All";
        }

        [ObjectiveCMessage("hiddenString")]
        public static NSString HiddenString(this NSRunningApplication runningApplication)
        {
            return runningApplication.IsHidden ? "Well Yes" : "In Fact Not";
        }
    }
}
  1. The ObjectiveCCategory attribute is used to marked a class containing extension methods for an exposition in the Objective-C runtime. When the assembly is loaded, the Monobjc bridge searches for every class marked with an ObjectiveCCategory attribute to expose it in the Objective-C runtime. The parameter is mandatory and is the Objective-C class which is extended by the new methods.
  2. A .NET class containing extension methods that want to be exposed to the Objective-C runtime has no inheritance requirements. It only needs to be static.
  3. The ObjectiveCMessage attribute is used to marked an extension method for an exposition in the Objective-C runtime. The attribute's parameter is the selector that will be used as the Objective-C selector for the exposed class. Note that the first paramater should be of type of the extended Objective-C class.
  4. The exposed method must be public and static, and be a valid extension method.