Skip to content

Calling AddError in the DefaultValueFactory will cause exception when showing help #2640

Closed

Description

@FMsrAtLapl

Calling AddError in the DefaultValueFactory will cause an exception when showing help
(provided the condition which triggers the error exists)

Help seemingly tries to create any default value, and in case it needs to call the AddError ( )-method
it tries to add to an internal structure which does not exist in "help-mode"

Probably it is not the best idea to add errors when creating default values
but then I took this example from the
Microsoft Tutorial

Option<FileInfo> fileOption = new("--file")
{
    Description = "An option whose argument is parsed as a FileInfo",
    Required = true,
    DefaultValueFactory = result =>
    {
        if (result.Tokens.Count == 0)
        {
            return new FileInfo("sampleQuotes.txt");

        }
        string filePath = result.Tokens.Single().Value;
        if (!File.Exists(filePath))
        {
            result.AddError("File does not exist");
            return null;
        }
        else
        {
            return new FileInfo(filePath);
        }
    }
};

Activity

  1. jonsequitur commented on Jul 28, 2025

    @jonsequitur
    Contributor

    Can you provide more details or a more complete repro? I wasn't able to reproduce any issue related to AddError here.

  2. FMsrAtLapl commented on Jul 29, 2025

    @FMsrAtLapl
    Author

    Here is a stripped down, but complete version of the program:

    1. We have a compare-Copmmand.

    2. a. The DefaultValueFactory of the command compare expects a token which it will use for building the default value.
      2.b. If it doesn't find a token, it raises an error.

    3. Now when you call help for this command:
      CmdLineDemo compare --help

    you get an unhandled exception
    when the help system is going to explain the use of the options for the compare command.

    Hello, World!
    Description:
    compares two files

    Nutzung:
    CmdLineDemo compare [options]

    Unhandled exception: System.NullReferenceException: Object reference not set to an instance of an object.
    at System.CommandLine.Parsing.ArgumentResult.AddError(String errorMessage)
    at CmdLineDemo.CompareCommandCreator.<>c.b__0_1(ArgumentResult result) in C:\Users\XXXXXX.XXXXr\Temp\DemoError\CmdLineDemo\Program.cs:line 43
    at System.CommandLine.Argument1.GetDefaultValue(ArgumentResult argumentResult) at System.CommandLine.Argument.GetDefaultValue() at System.CommandLine.Option.GetDefaultValue() at System.CommandLine.Help.HelpBuilder.Default.GetArgumentDefaultValue(Symbol parameter) at System.CommandLine.Help.HelpBuilder.GetArgumentDefaultValue(Symbol parent, Symbol parameter, Boolean displayArgumentName, HelpContext context) at System.CommandLine.Help.HelpBuilder.<>c__DisplayClass21_1.<GetTwoColumnRow>b__4(Symbol argument) at System.Linq.Enumerable.ArraySelectIterator2.MoveNext()
    at System.String.Join(String separator, IEnumerable`1 values)
    at System.CommandLine.Help.HelpBuilder.<>c__DisplayClass21_0.g__GetSymbolDefaultValue|2(Symbol symbol)
    at System.CommandLine.Help.HelpBuilder.<>c__DisplayClass21_0.g__GetOptionOrCommandRow|0()
    at System.CommandLine.Help.HelpBuilder.GetTwoColumnRow(Symbol symbol, HelpContext context)
    at System.CommandLine.Help.HelpBuilder.Default.<>c.b__11_0(HelpContext ctx)
    at System.CommandLine.Help.HelpBuilder.Write(HelpContext context)
    at System.CommandLine.Help.HelpAction.Invoke(ParseResult parseResult)
    at System.CommandLine.Invocation.InvocationPipeline.Invoke(ParseResult parseResult)

    using System.CommandLine;
    namespace CmdLineDemo;
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            var rootCommand = RootCommandCreator.CreateRootCommand();
            ParseResult parseResult = rootCommand.Parse(args);
            parseResult.Invoke();
        }
    }
    internal static class RootCommandCreator
    {
        public static Command CreateRootCommand()
        {
    
            RootCommand rootCommand = new("Any Testrunner")
            {
            };
            Command compareCommand = CompareCommandCreator.CreateCommand();
            rootCommand.Subcommands.Add(compareCommand);
            return rootCommand;
        }
    }
    internal static class CompareCommandCreator
    {
        public static Command CreateCommand()
        {
            Option<DirectoryInfo?> excelPathOption = new("--excel-path")
            {
                Description = "Path to Excel",
                Required = false,
                DefaultValueFactory = result =>
                {
                    if (result.Tokens.Count == 0)
                    {
                        result.AddError("No path given");
                        return null;
                    }
    
                    string directoryPath = result.Tokens.Single().Value;
                    return new(directoryPath);
                }
            };
            Command compareCommand = new("compare", "compares two files") { excelPathOption };
            compareCommand.SetAction(result => { Console.WriteLine("Command executed"); });
            return compareCommand;
        }
    }
    
    
  3. added
    bug
    and removed on Jul 31, 2025
  4. added this to the 2.0.0-beta7 milestone on Jul 31, 2025
  5. self-assigned this
    on Jul 31, 2025
  6. added 2 commits that reference this issue on Jul 31, 2025
    2538622
    98219f1
  7. added a commit that references this issue on Jul 31, 2025
    1f2adb8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Area-APIbug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions