delphinulldelphi-xevariants

Managing null values in variants using Delphi


I'm working with a COM component which exposes a lot of Variant properties, but sometimes these values are null. When I try to convert these values to string (or another Delphi type) the application raises an exception like this:

Could not convert variant of type (Null) into type (String)

But if I use .net to call the same properties and the values are null, no exceptions are raised and the null values are treated as empty strings.

My question there is a way to handle these null values from Delphi avoiding these exceptions?

Thanks in advance.


Solution

  • Try setting NullStrictConvert to False.

    As it's a global variable I use it like follows to minimize side effects:

    var
      OldNullStrictConvert: Boolean;
    begin
      OldNullStrictConvert := NullStrictConvert;
      NullStrictConvert := False;
      try
        // code containing conversions
      finally
        NullStrictConvert := OldNullStrictConvert;
      end;
    end;
    

    (In reality I have made a guardian interface out of this.)

    NB: Where it's feasible I prefer code like Warren's.