Skip to content

Getting started

Alex Kamsteeg edited this page Jun 30, 2021 · 8 revisions

Installation

First, we need to install the AtleX.CommandLineArguments package in our project. Since it's available as a NuGet package on NuGet.org, we can use the NuGet package manager or the package manager console:

install-package AtleX.CommandLineArguments

See Home for the list of supported frameworks.

First steps

AtleX.CommandLineArguments parses the command line arguments supplied by the user to a strongly typed object. So, first we're going to create an object that will hold our values. For that we need a new class that extends Arguments, a built-in class from the library.

The names of the properties in our class map to the names of the arguments on the command line. Let's say we want the user to supply their name with a command line argument called Name, that means our class for the arguments looks like this:

internal sealed class CliArguments : Arguments
{
    public string Name
    {
        get;
        set;
    }
}

To parse that, we use the CommandLineArguments class which has a static TryParse<T>(string[], out T) method to do all the work for us. It returns true when the library successfully parsed the arguments to the object, and false otherwise.

So, in our Main(string[]) method in Program we add the following:

public class Program
{
    static void Main(string[] args)
    {
        if (!CommandLineArguments.TryParse<CliArguments>(args, out var cliArguments))
        {
            // Oops, something was wrong
        }
        else
        {
            Console.WriteLine($"Hello {cliArguments.Name}!");
        }
    }
}

When the user starts our application with the argument we show a greeting:

c:\sample.exe /Name Alex
Hello Alex!

Next steps

See configuring AtleX.CommandLineArguments and required command line arguments for more information.

Clone this wiki locally