Add new comment

Nullables in Free Pascal and Delphi

An example of generic implementation of nullable value types in FreePascal (easy to adapt for Delphi).

program Nullables;
 
{$mode objfpc}{$H+}
 
uses
  Classes, SysUtils;
 
type
  generic TNullable<T> = object
    private
      FHasValue: boolean;
      FValue: T;
      function GetValue: T;
      procedure SetValue(AValue: T);
    public
      procedure Clear;
      property HasValue: boolean read FHasValue;
      property Value: T read GetValue write SetValue;
  end;
 
  TNullableInt = specialize TNullable<integer>;
  operator := (Src: integer) Dest : TNullableInt;
  begin
    Dest.Value := Src;
  end;
 
{ TNullable }
function TNullable.GetValue: T;
begin
  if FHasValue then
     Result := FValue
  else
    raise Exception.Create('Variable has no value');
end;
 
procedure TNullable.SetValue(AValue: T);
begin
  FValue := AValue;
  FHasValue := true;
end;
 
procedure TNullable.Clear;
begin
  FHasValue := false;
end;
 
procedure ShowValue(Value: TNullableInt);
begin
  if Value.HasValue then
     writeln('Value: ', Value.Value)
  else
    writeln('Value: NULL')
end;
 
var
  MyValue: TNullableInt;
begin
  MyValue.Clear;
  ShowValue(MyValue);
  MyValue := 123;
  ShowValue(MyValue);
end.

Result:

Value: NULL
Value: 123