Difference between revisions of "How to use nullable types"

From Free Pascal wiki
Jump to navigationJump to search
(Fix wording as the other page does not list the code but a URL)
Line 3: Line 3:
  
 
Here is a small example of how to use the [[Nullable types|nullable types]] in [[Mode Delphi|Delphi mode ( <syntaxhighlight lang="pascal" enclose="none">{$mode Delphi}</syntaxhighlight> )]].
 
Here is a small example of how to use the [[Nullable types|nullable types]] in [[Mode Delphi|Delphi mode ( <syntaxhighlight lang="pascal" enclose="none">{$mode Delphi}</syntaxhighlight> )]].
The [[Unit|unit's]] nullable [[Source code|source code]] can be found on the [[Nullable types|nullable types]] wiki page.
+
The [[Unit|unit's]] nullable [[Source code|source code]] is referenced on the [[Nullable types|nullable types]] wiki page.
  
 
<syntaxhighlight lang="pascal">
 
<syntaxhighlight lang="pascal">

Revision as of 13:07, 5 March 2022

English (en)


Here is a small example of how to use the nullable types in Delphi mode ( {$mode Delphi} ). The unit's nullable source code is referenced on the nullable types wiki page.

program temperatureproject;
{$mode delphi}{$H+}
uses Nullable, SysUtils;

type

NullableFloat = TNullable<single>;

var
  weekDayTemperature : array[1..7] of  NullableFloat;
  max, min :NullableFloat;
  i, values,code:integer;
  sum, temp:single;
  s:string;
begin
  for i:= 1 to 7 do  weekDayTemperature[i].Clear;
  min.Clear;
  max.Clear;
  // ...
  for i:= 1 to 7 do
    begin
      writeln('Enter the temperature on '+ DefaultFormatSettings.LongDayNames[i] );
      readln(s);
      Val (s,temp,code);
      if code = 0 then weekDayTemperature[i].SetValue(temp);
    end;
  // ...
  sum := 0;
  values := 0;
  for i:= 1 to 7 do
     begin
       if weekDayTemperature[i].HasValue then
          begin
            if min.HasValue then
              begin
                if min.GetValue > weekDayTemperature[i].GetValue
                  then min.SetValue( weekDayTemperature[i].GetValue);
              end
                else  min.SetValue( weekDayTemperature[i].GetValue);
            if max.HasValue then
              begin
                if max.GetValue < weekDayTemperature[i].GetValue
                  then max.SetValue( weekDayTemperature[i].GetValue);
              end
              else max.SetValue( weekDayTemperature[i].GetValue);
            inc(values);
            sum := sum + weekDayTemperature[i].GetValue;
          end;
     end;
  if min.HasValue then
    begin
      writeln('The average week temperature was ',sum/values:0:1,' degrees.');
      writeln('The minimum temperature was ',min.GetValue:0:1,' degrees.');
      writeln('The maximum temperature was ',max.GetValue:0:1,' degrees.');
    end;
  //...
  writeln('Press any key to continue!');
  readln;
end.

See also