I’m trying to add a boolean flag option to my System.CommandLine C#/.NET program. However, nothing I specify when I run the program seems to result in a true
value in my command handler:
<code>using System.CommandLine;
using System.CommandLine.Parsing;
using System.CommandLine.Builder;
using System.CommandLine.NamingConventionBinder;
var rootCommand = new RootCommand
{
Description = "System.CommandLine Example"
};
var exampleOption = new Option<bool>(
new[] { "--opt", "-o" },
"Set an example boolean option to true"
);
var exampleCommand = new Command("command", "Example command")
{
Handler = CommandHandler.Create<bool>((flag) =>
{
Console.WriteLine($"Ran example command with opt={flag}");
})
};
exampleCommand.AddOption(exampleOption);
rootCommand.AddCommand(exampleCommand);
var parser = new CommandLineBuilder(rootCommand)
.UseHelp()
.UseDefaults()
.Build();
await parser.InvokeAsync(args);
</code>
<code>using System.CommandLine;
using System.CommandLine.Parsing;
using System.CommandLine.Builder;
using System.CommandLine.NamingConventionBinder;
var rootCommand = new RootCommand
{
Description = "System.CommandLine Example"
};
var exampleOption = new Option<bool>(
new[] { "--opt", "-o" },
"Set an example boolean option to true"
);
var exampleCommand = new Command("command", "Example command")
{
Handler = CommandHandler.Create<bool>((flag) =>
{
Console.WriteLine($"Ran example command with opt={flag}");
})
};
exampleCommand.AddOption(exampleOption);
rootCommand.AddCommand(exampleCommand);
var parser = new CommandLineBuilder(rootCommand)
.UseHelp()
.UseDefaults()
.Build();
await parser.InvokeAsync(args);
</code>
using System.CommandLine;
using System.CommandLine.Parsing;
using System.CommandLine.Builder;
using System.CommandLine.NamingConventionBinder;
var rootCommand = new RootCommand
{
Description = "System.CommandLine Example"
};
var exampleOption = new Option<bool>(
new[] { "--opt", "-o" },
"Set an example boolean option to true"
);
var exampleCommand = new Command("command", "Example command")
{
Handler = CommandHandler.Create<bool>((flag) =>
{
Console.WriteLine($"Ran example command with opt={flag}");
})
};
exampleCommand.AddOption(exampleOption);
rootCommand.AddCommand(exampleCommand);
var parser = new CommandLineBuilder(rootCommand)
.UseHelp()
.UseDefaults()
.Build();
await parser.InvokeAsync(args);
When I invoke it, I get this result:
<code>SystemCommandLineExample.exe command --opt=true
Ran example command with opt=False
</code>
<code>SystemCommandLineExample.exe command --opt=true
Ran example command with opt=False
</code>
SystemCommandLineExample.exe command --opt=true
Ran example command with opt=False
What am I doing wrong?