VariantStrings (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of VarToStr, VarToStrDef, VarToWideStr and VarToWideStrDef methods defined in the Variants unit. VarToStr is equivalent to VarToWideStr and VarToStrDef is equivalent to VarToWideStrDef.

Code

var
  LVar: Variant;

begin
  { Assign a non-string value to the variant. }
  LVar := 10.6;

  { Print the Variant's value and catch the exception. If the variant cannot be 
    converted to a string print another message. }
  try
    Writeln(VarToStr(LVar));
  except
    Writeln('not a string');
  end;
  
  { Use VarToStrDef instead. This method ensures that if LVar is not convertable to string a default 
    value is used. }
  Writeln(VarToStrDef(LVar, 'not a string'));

  { Print the Variant's value and catch the exception. If the variant cannot be 
    converted to a wide string print another message. }
  try
    Writeln(VarToWideStr(LVar));
  except
    Writeln('empty string');
  end;
  
  { Use VarToWideStrDef instead. This method ensures that if LVar is not convertable to wide string a default 
    value is used. }
  Writeln(VarToWideStrDef(LVar, 'empty string'));
  Readln;
end.

Uses