fclp / fluent-command-line-parser

A simple, strongly typed .NET C# command line parser library using a fluent easy to use interface
Other
530 stars 86 forks source link

SetDefault and Callback when using DateTime results in 01-01-0001 output #90

Open VisualBean opened 6 years ago

VisualBean commented 6 years ago

We are using the following code

parser.Setup(arg => arg.ExecutionDate)
                .As('d', "date")
                .SetDefault(DateTime.Today)
                .Callback((date) =>
                {
                    if (date > DateTime.Today)
                        date = DateTime.Today;
                });
parser.Object;

When we are NOT providing the -d parser.Object returns ExecutionDate as 01-01-0001 and not datetime.today

siywilliams commented 6 years ago

Hi @VisualBean

The callback is there to allow you to do something with the final parsed value, it was the only way to return the parsed value in the first versions of fclp.

The callback shouldn't be used when using the Generic Fluent Command Line Parser which is what you are doing as it can replace the internal function being called as part of the builder object. I did add a comment on the xml documentation "Do no use this if you are using the Fluent Command Line Builder" for that function, but it can be easily missed and people probably don't know the difference between the builder and the original parser (I introduced builder for backwards compatibility).

As there is no built in API to validate a value I would suggest you move that functionality to your setter on the ExecutionDate property and remove the callback use.

public DateTime ExecutionDate
{
  get { return _executionDate; }
  set
  {
    if (value > DateTime.Today)
    {
      value = DateTime.Today;
    }
    _executionDate = value;
  }
}

static void Main(string[] args)
{
  var fclp = new FluentCommandLineParser();
  fclp.Setup(arg => arg.ExecutionDate)
        .As('d', "date")
        .SetDefault(DateTime.Today); 
}