srayner
srayner

Reputation: 1839

How can I make a TDate parameter optional in Delphi?

My class looks like this;

type TBatchFilter = class(TObject)
  private
    FBatchNo: string;
    FLine: string;
    FCutoffDate: TDate;
  public
    constructor Create(ABatchNo, ALine: string; ACutoffDate: TDate); overload;
    constructor Create(ABatchFilter: TBatchFilter); overload;
    property BatchNo: string read FBatchNo;
    property Line: string read FLine;
    property CutoffDate: TDate read FCutoffDate;
end;

I want to make the ACutoffDate:TDate parameter optional. I was thing of calling the constructor like this;

MyBatchFilter := TBatchFilter('BATCH1', 'LINE1', nil);

Then in the constructor have something like this;

if (ACuttoffDate = nil) then
  dosomething
else
  dosomethingelse;

But i can't pass nil as a parameter. I don't really want to overload the constructor any further.

Upvotes: 0

Views: 529

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597111

You can pass the value by pointer:

constructor Create(ABatchNo, ALine: string; ACutoffDate: PDate = nil); overload;

if (ACuttoffDate = nil) then
  dosomething
else
  dosomethingelse(ACuttoffDate^);

TBatchFilter.Create('123', 'line');

TBatchFilter.Create('123', 'line', @SomeDateVar);

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613282

There are two obvious ways to tackle this:

  1. Add another overloaded constructor that omits the date parameter.
  2. Make the date parameter have a default value that is some sentinel value that has no meaning.

You've attempted to use nil as a sentinel, but the sentinel has to be a valid value for the type. And nil is not. You'll need to pick a suitable value. Perhaps zero. Or a very large positive or negative value. Whatever you choose, declare a named constant to give your code semantic clarity.

Upvotes: 5

Related Questions