commandlineparser / commandline

The best C# command line parser that brings standardized *nix getopt style, for .NET. Includes F# support
MIT License
4.46k stars 473 forks source link

Handling the CS8618 warning (Non-nullable property) #925

Closed ajtruckle closed 3 months ago

ajtruckle commented 3 months ago

Recently started using .NET8 for a console application and I get warnings with all my options.

As an example:

[Option("log", Required = true, HelpText = "Path to log file. Eg: --log \".\\logfile.txt\"")]
public string LogFile { get; set; }

The compiler says:

warning CS8618: Non-nullable property LogFilemust contain a non-null value when exiting constructor. Consider declaring the property as nullable.

The IDE gives two suggestions:

  1. Add the requiredkeyword.
  2. Declare it as nullable.

My Options class does not have a constructor, based on the working samples. I would appreciate guidance on the right way to address this so that the CommandLindParser mechanism doesn't break Thank you! I apologize in advanced if I have overlooked some official documentation.

ajtruckle commented 3 months ago

I have made all the string options nullable:

public class Options
{
    [Option("log", Required = true, HelpText = "Path to log file. Eg: --log \".\\logfile.txt\"")]
    public string? LogFile { get; set; }
    [Option('c', "create", Required = false, HelpText = "Creates an empty CSV. Eg: -c --csv \".\\file.csv\"")]
    public bool CreateCsvFile { get; set; }
    [Option("csv", Required = false, HelpText = "Specifies CSV filename. Eg: --csv \".\\file.csv\"")]
    public string? CsvFilePath { get; set; }
    [Option("xml", Required = false, HelpText = "Specifies XML filename. Eg: --xml \".\\file.xml\"")]
    public string? XmlFilePath { get; set; }
    [Option('t', "test", Required = false, HelpText = "For testing. Eg: -t --csv \".\\file.csv\"  --xml \".\\file.xml\"")]
    public bool DoTest { get; set; }
    [Option("lang", Required = false, HelpText = "Specifies the language code. Eg: --lang ENG")]
    public string? LanguageCode { get; set; }
    [Option("json", Required = false, HelpText = "Specifies the JSON text. Eg: --json \"json\"")]
    public string? Json { get; set; }
    [Option("mode", Required = false, HelpText = "Specifies the import mode. Eg: --mode clm")]
    public string? ImportMode { get; set; }
}

Com[iles fine and appears to be working correctly! 😊