Configuring System.CommandLine with a class

Paul Wheeler
1 min readMay 9, 2020
Photo by Florian Olivo on Unsplash

I’ve been playing around with building a simple application that I wanted to have command line support. While researching the available .Net options for command-line parsing I discovered the System.CommandLine library. It appears that it was created to support all the new .Net commands like dotnet run so I assume it would work just fine for my needs.

The first issue I ran into though was that I could only find examples of how to use it with a method, mapping the command-line argument to the method parameters using an extension called DragonFruit. But what I wanted to do was to be able to define my command using a class with properties instead. I built a simple extension method ConfigureFromClass<T> that would allow the use of the ComponentModel Annotations to configure the Options. This is not a complete implementation but should be a good start for anyone trying to accomplish something similar.

Here is the simple usage (full gist code below)
var command = new RootCommand();
command.ConfigureFromClass<Hello>(hello =>
return command.Invoke(args);

You can play around with it using DotNetFiddle: