Failing to assign a null variant value to a Nullable<T> property.

I recently changed my code to directly use a DataSet query to load values to a class because it is faster than using TObjectManager and I needed more performance. Talking about an object list of many thousands of items.

But now when I try to assign a null value to a Nullable property I get an exception.


TMyClass = class
myproperty1: Nullable;
myproperty2: Nullable;
myproperty3: Nullable;

and trying this gives me the exception:
myClass.myproperty1 := myDataSet.FindField('somefield').AsVariant;
myClass.myproperty2 := myDataSet.FindField('somefield').AsVariant;
myClass.myproperty3 := myDataSet.FindField('somefield').AsVariant;

if the dataset field is null, I get an exception.

What can I do to fix this?


You cannot assign a Variant NULL to the Nullable type.
To see null to a Nullable variable, you should use the Empty property:

myClass.myproperty1 := Nullable<string>.Empty;

How does TObjectManager works then?
When loading data from a dataset with TObjectManager all null values are set properly.

I managed to solve this by adding this method to the Nullable record.
class operator Implicit(Value: Variant): Nullable<T>;
But I'm sure this is not the best approach.


It handles the value manually as I mentioned above.

  if Value.IsEmpty then
    SetNullableValue(Nullable, Value);