Getting started with macOS

What you will need

Hello world

First, build a simple hello world example in C#.

Create C# sample

Open Visual Studio for Mac, create a new Mac Class Library project named hello-from-csharp, and save it to ~/Projects/hello-from-csharp.

Replace the code in the MyClass.cs file with the following snippet:

using AppKit;
public class MyNSView : NSTextView
{
	public MyNSView ()
	{
		Value = "Hello from C#";
	}
}

Build the project. The resulting assembly will be saved as ~/Projects/hello-from-csharp/hello-from-csharp/bin/Debug/hello-from-csharp.dll.

Bind the managed assembly

Once you have a managed assembly, bind it by invoking .NET Embedding.

As described in the installation guide, this can be done as post-build step in your project, with a custom MSBuild target, or manually:

cd ~/Projects/hello-from-csharp
objcgen ~/Projects/hello-from-csharp/hello-from-csharp/bin/Debug/hello-from-csharp.dll --target=framework --platform=macOS-modern --abi=x86_64 --outdir=output -c --debug

The framework will be placed in ~/Projects/hello-from-csharp/output/hello-from-csharp.framework.

Use the generated output in an Xcode project

Open Xcode and create a new Cocoa Application. Name it hello-from-csharp and select the Objective-C language.

Open the ~/Projects/hello-from-csharp/output directory in Finder, select hello-from-csharp.framework, drag it to the Xcode project and drop it just above the hello-from-csharp folder in the project.

Drag and drop framework

Make sure Copy items if needed is checked in the dialog that pops up, and click Finish.

Copy items if needed

Select the hello-from-csharp project and navigate to the hello-from-csharp target's General tab. In the Embedded Binary section, add hello-from-csharp.framework.

Embedded binaries

Open ViewController.m, and replace the contents with:

#import "ViewController.h"

#include "hello-from-csharp/hello-from-csharp.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    MyNSView *view = [[MyNSView alloc] init];
    view.frame = CGRectMake(0, 200, 200, 200);
    [self.view addSubview: view];
}

@end

Finally, run the Xcode project, and something like this will show up:

Hello from C# sample running in the simulator

A more complete and better-looking sample is available here.