ZetCode

C# Cocona

last modified October 18, 2026

In this article we create console applications in C# using the Cocona library.

Cocona is a library which makes it easy and fast to build console applications on .NET. The library mimics the ASP.NET Core Minimal API: a command is a delegate or a method, and its parameters become the command line options and arguments. The generated applications behave like standard Unix tools, with --long and -s options, generated help, and meaningful exit codes.

There are two versions of the library: Cocona and Cocona.Lite. The lite version has less overhead and fewer features. It has no logging, dependency injection, or configuration, and it does not support multiple values of an option (arrays). The examples use the lite version unless noted.

$ dotnet add package Cocona.Lite

We add the lite package to the project. For the full version, we add the Cocona package instead; the two must not be mixed in one project. The examples were run with version 2.2, the latest release at the time of writing.

Note: Cocona has not had a new release for some time. It works with current .NET, but if long-term support matters, consider Microsoft's System.CommandLine as an alternative. See also the command line arguments tutorial.

C# Cocona simple example

We have a very simple console application.

Program.cs
using Cocona;

CoconaLiteApp.Run((string name) =>
{
    Console.WriteLine($"Hello {name}");
});

If our application has only one command, we can directly use the CoconaLiteApp.Run method. Cocona creates a command-line option from the method parameter (name). A parameter without a default value is required.

$ dotnet run -- --name Peter
Hello Peter

We pass a value to the --name option. The program responds with a hello message. The double dash separates the arguments of the dotnet tool from those of our program.

$ dotnet run -- --help
Usage: app [--name <String>] [--help] [--version]

app

Options:
  --name <String>     (Required)
  -h, --help         Show help message
  --version          Show version

Cocona automatically creates the application help and the --version option. Since the dotnet command also has the --help option, we must precede ours with --. When a required option is missing, the application prints an error and returns a non-zero exit code:

$ dotnet run
Error: Option '--name' is required. See '--help' for usage.

The previous code was a shortened version of the following one:

Program.cs
using Cocona;

var builder = CoconaLiteApp.CreateBuilder();
var app = builder.Build();

app.AddCommand((string name) =>
{
    Console.WriteLine($"Hello {name}");
});

app.Run();

In this code example, we build the Cocona application with a builder and add a new command with AddCommand.

app.Run();

The Run method starts the Cocona enabled application. It parses the command line, finds the command, converts the values to the types of the parameters, and calls the delegate.

Class-based example

In class-based applications, public methods are automatically transformed into commands.

Program.cs
using Cocona;

class Program
{
    static void Main(string[] args)
    {
        CoconaLiteApp.Run<Program>(args);
    }

    public void Message(string name, int age)
    {
        Console.WriteLine($"{name} is {age} years old");
    }
}

The program accepts two options: --name and --age. The types of the parameters decide how the values are converted.

$ dotnet run -- --name John --age 34
John is 34 years old

$ dotnet run -- --name John --age abc
Error: Option 'age' requires Int32 value. 'abc' cannot be converted to Int32 value.

The conversion error is reported in a readable way. The exit code is 1 for errors, and 129 for the help output.

Multiple named commands

We can add multiple named commands, like git add and git commit.

Program.cs
using Cocona;

var app = CoconaLiteApp.Create();

app.AddCommand("add", () => { Console.WriteLine("add command"); });
app.AddCommand("remove", () => { Console.WriteLine("remove command"); });
app.AddCommand("show", () => { Console.WriteLine("show command"); });

app.Run();

The example adds three named commands.

app.AddCommand("add", () => { Console.WriteLine("add command"); });

The first parameter is the name of the command. The second parameter is the delegate with the body of the command.

$ dotnet run -- add
add command

$ dotnet run -- --help
Usage: app [command]

app

Commands:
  add
  remove
  show

Options:
  -h, --help    Show help message
  --version     Show version

Options, arguments, and defaults

A parameter is an option by default (--name value). With the Argument attribute, it becomes a positional argument. The Option attribute gives an option a short name or a custom long name and a description. A default value makes the option optional.

Program.cs
using Cocona;

var app = CoconaLiteApp.Create();

app.AddCommand((
    [Argument(Description = "The file to copy")] string source,
    [Argument(Description = "The destination")] string destination,
    [Option('n', Description = "How many times")] int count = 1,
    [Option("upper", Description = "Convert the names to upper case")] bool upperCase = false) =>
{
    for (int i = 0; i < count; i++)
    {
        var (s, d) = upperCase ? (source.ToUpper(), destination.ToUpper()) : (source, destination);
        Console.WriteLine($"copy {s} -> {d}");
    }
}).WithDescription("Copies a file");

app.Run();

The program simulates a copy command.

[Argument(Description = "The file to copy")] string source,

The first two parameters are positional arguments, taken in the order of the declaration.

[Option('n', Description = "How many times")] int count = 1,
[Option("upper", Description = "Convert the names to upper case")] bool upperCase = false

The count option is also available as -n, and its default is 1. A bool parameter is a flag; the option's name is set to --upper, instead of the generated --upper-case. The description is shown in the help.

}).WithDescription("Copies a file");

WithDescription sets the description of the command.

$ dotnet run -- a.txt b.txt -n 2
copy a.txt -> b.txt
copy a.txt -> b.txt

$ dotnet run -- a.txt b.txt --upper
copy A.TXT -> B.TXT

$ dotnet run -- --help
Usage: app [--count <Int32>] [--upper] [--help] [--version] source destination

Copies a file

Arguments:
  0: source         The file to copy (Required)
  1: destination    The destination (Required)

Options:
  -n, --count <Int32>    How many times (Default: 1)
  --upper                Convert the names to upper case
  -h, --help             Show help message
  --version              Show version

$ dotnet run -- a.txt
Error: Argument 'destination' is required. See '--help' for usage.

Flags

Flags are bool options. A short name is added with the Option attribute.

Program.cs
using Cocona;

var app = CoconaLiteApp.Create();

app.AddCommand(([Option('f')] bool force, [Option('r')] bool recursive) =>
{
    Console.WriteLine($"force={force}, recursive={recursive}");
});

app.Run();

The example adds two flags: -f and -r.

$ dotnet run -- -f -r
force=True, recursive=True

$ dotnet run -- -fr
force=True, recursive=True

$ dotnet run -- -f
force=True, recursive=False

We can use both the -f -r and -fr variations, as in Unix tools. A flag that is not present is false.

Commands in a class

With a class, we get a full command-line tool: each public method becomes a command, and the attributes tune the behaviour.

Program.cs
using Cocona;

CoconaLiteApp.Run<Commands>(args);

class Commands
{
    [Command(Description = "Adds an item")]
    public void Add([Argument] string item, int priority = 5) => Console.WriteLine($"added {item} with priority {priority}");

    [Command(Description = "Removes an item")]
    public void Remove([Argument] string item, [Option('f')] bool force) =>
        Console.WriteLine($"removed {item}{(force ? " (forced)" : "")}");

    [PrimaryCommand]
    public void Default() => Console.WriteLine("no command given");

    [Command("list-all")]
    [Command(Description = "Lists the items")]
    public void List() => Console.WriteLine("listing");

    [Ignore]
    public void NotACommand() { }
}

The class has several commands.

CoconaLiteApp.Run<Commands>(args);

The generic Run method scans the class for public methods. The name of a command is the method name in kebab-case (lower case); the Command attribute changes it or adds a description and aliases.

[PrimaryCommand]
public void Default() => Console.WriteLine("no command given");

The primary command runs when the user gives no command name. Methods marked with Ignore are not commands.

$ dotnet run -- add apple
added apple with priority 5

$ dotnet run -- add pear --priority 1
added pear with priority 1

$ dotnet run -- remove x -f
removed x (forced)

$ dotnet run
no command given

$ dotnet run -- --help
Usage: app [command]

app

Commands:
  add         Adds an item
  remove      Removes an item
  list-all    Lists the items

Options:
  -h, --help    Show help message
  --version     Show version

$ dotnet run -- add --help
Usage: app add [--priority <Int32>] [--help] item

Adds an item

Arguments:
  0: item     (Required)

Options:
  --priority <Int32>     (Default: 5)
  -h, --help            Show help message

Validation and exit codes

The standard attributes from System.ComponentModel.DataAnnotations, such as Range, EmailAddress, and MaxLength, can decorate the parameters, and Cocona validates the values before the command runs. The value returned from the delegate becomes the exit code of the process.

Program.cs
using System.ComponentModel.DataAnnotations;
using Cocona;

CoconaLiteApp.Run(([Range(1, 100)] int percent, [Option('e')][EmailAddress] string email) =>
{
    Console.WriteLine($"{percent}% for {email}");
});

The program validates a percentage and an e-mail address.

$ dotnet run -- --percent 50 -e a@b.c
50% for a@b.c

$ dotnet run -- --percent 500 -e a@b.c
Error: The field percent must be between 1 and 100.

$ dotnet run -- --percent 5 -e nope
Error: The email field is not a valid e-mail address.

In the next example, the command returns an int, which is the exit code. Scripts use it to react to failures, which is the way command-line tools should communicate.

Program.cs
using Cocona;

CoconaLiteApp.Run((string path) =>
{
    if (!File.Exists(path))
    {
        Console.Error.WriteLine($"file {path} not found");
        return 2;
    }

    Console.WriteLine("ok");
    return 0;
});
$ dotnet run -- --path /nonexistent
file /nonexistent not found
$ echo $?
2

$ dotnet run -- --path /etc/hostname
ok
$ echo $?
0

Error messages go to the standard error stream with Console.Error, so that they do not mix with the regular output when the output of the tool is redirected to a file or piped to another program.

An array of values

An option can take multiple values, which are collected into an array. This option is not supported in the lite Cocona application, so this example uses the full Cocona package.

Program.cs
using Cocona;

var app = CoconaApp.CreateBuilder().Build();

app.AddCommand(([Option('N')] string[] names) =>
{
    foreach (var name in names)
    {
        Console.WriteLine(name);
    }
});

app.Run();

The program accepts one or more values for the -N option.

app.AddCommand(([Option('N')] string[] names) =>

An array of strings is decorated with the [Option('N')] attribute. The value of the option can be repeated.

$ dotnet run -- -NPaul -NJane -NJohn -NLucy
Paul
Jane
John
Lucy

The short option can be written with the value attached (-NPaul) or separated by a space, and repeated for each value. The help shows the option as -N, --names <String>....

Dependency injection and logging

The full Cocona is built on the generic host of .NET, so a command receives the registered services and loggers as parameters, just like an ASP.NET Core endpoint.

Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Cocona;

var builder = CoconaApp.CreateBuilder();
builder.Services.AddSingleton<IGreeter, Greeter>();

var app = builder.Build();

app.AddCommand((IGreeter greeter, string name, ILogger<Program> logger) =>
{
    logger.LogInformation("greeting {Name}", name);
    Console.WriteLine(greeter.Greet(name));
});

app.Run();

interface IGreeter { string Greet(string name); }
class Greeter : IGreeter { public string Greet(string name) => $"Hello, {name}!"; }

The program registers a service, and the command uses it.

builder.Services.AddSingleton<IGreeter, Greeter>();

The services are registered in the same way as in other .NET hosts. Configuration (appsettings.json, environment variables) is available as well.

app.AddCommand((IGreeter greeter, string name, ILogger<Program> logger) =>

Parameters whose types are registered services are injected; the others become options. The ILogger parameter gives us logging to the console.

$ dotnet run -- --name Ann
info: Program[0]
      greeting Ann
Hello, Ann!

Source

Cocona Github page

In this article we have created console applications in C# using Cocona.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.