delphi - Setting an enumerated type var to nil -


maybe (probably) silly question, didn't find answer...

please, check 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' , 'pointer')   if (str = 'type1')     result := type1 else   if (str = 'type2')     result := type2 else   if (str = 'type3')     result := type3; end; 

please, how can set nil / null / empty custom type var, can check function result , avoid problems?

an enumerated type cannot nil. must take 1 of defined enumeration values.

you have few options. can add enum:

type   tcustomtype = (novalue, type1, type2, type3); 

you can use nullable type. instance spring has nullable<t>.

you raise exception if no value found.

function strtocustomtype(str: string): tcustomtype; begin   if (str = 'type1')     result := type1    else if (str = 'type2')     result := type2    else if (str = 'type3')     result := type3   else     raise emyexception.create(...); end; 

or can use tryxxx pattern.

function trystrtocustomtype(str: string; out value: tcustomtype): boolean; begin   result := true;   if (str = 'type1')     value := type1    else if (str = 'type2')     value := type2    else if (str = 'type3')     value := type3   else     result := false; end;  function strtocustomtype(str: string): tcustomtype; begin   if not trystrtocustomtype(str, result)     raise emyexception.create(...); end; 

Comments