Setting var to nil

Maybe (maybe) this is a stupid question, but I couldn't find an answer ...

Please check this hypothetical code:

type
  TCustomType = (Type1, Type2, Type3);

function CustomTypeToStr(CTp: TCustomType): string;
begin
  Result := '';
  case CTp of
    Type1: Result := 'Type1';
    Type2: Result := 'Type2';
    Type3: Result := 'Type3';
  end;
end;

function StrToCustomType(Str: string): TCustomType;
begin
  Result := nil;           <--- ERROR (Incompatible types: 'TCustomType' and 'Pointer')
  if (Str = 'Type1') then
    Result := Type1 else
  if (Str = 'Type2') then
    Result := Type2 else
  if (Str = 'Type3') then
    Result := Type3;
end;

      

Please, how can I set nil / null / empty for this custom var type so I can check the function result and avoid problems?

+3


source to share


1 answer


An enumerated type cannot be nil

. It must be one of the defined enumeration values.

You have several options. You can add another enum:

type
  TCustomType = (NoValue, Type1, Type2, Type3);

      

You can use a nullable type. For example, Spring has Nullable<T>

.



You can throw an exception if no value is found.

function StrToCustomType(Str: string): TCustomType;
begin
  if (Str = 'Type1') then
    Result := Type1 
  else if (Str = 'Type2') then
    Result := Type2 
  else if (Str = 'Type3') then
    Result := Type3
  else
    raise EMyException.Create(...);
end;

      

Or you can use a template TryXXX

.

function TryStrToCustomType(Str: string; out Value: TCustomType): Boolean;
begin
  Result := True;
  if (Str = 'Type1') then
    Value := Type1 
  else if (Str = 'Type2') then
    Value := Type2 
  else if (Str = 'Type3') then
    Value := Type3
  else
    Result := False;
end;

function StrToCustomType(Str: string): TCustomType;
begin
  if not TryStrToCustomType(Str, Result) then
    raise EMyException.Create(...);
end;

      

+4


source







All Articles