2

How do you assign null to a Delphi.net Nullable? I have a field which previously contained a value , I need to clear its value back to null.

depth : Nullable<Double>;

Procedure ClearDepth;
begin 
    depth := Nil;
end;

The above creates the error Error: E2010 Incompatible types : 'Nullable<System.Double>' and 'Pointer'. using Null in place of Nil gives the same error with Variant in place of Pointer. I wondered if I should be using a special constructor to generate a null nullable but I couldn't see one in the documentation?

The following works but doesn't seem like a great solution, can anyone suggest a better way?

Procedure ClearDepth;
var
    uninitialisedValue : Nullable<Double>;
begin 
    depth := uninitialisedValue;
end;
Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
Tom Carver
  • 962
  • 7
  • 17

2 Answers2

3

You need this syntax:

depth := Default(Nullable<Double>);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

The type Nullable<T> is a struct. That means it has a public parameterless constructor. In the case of this type, that's the value that represents null. In C#, you would use:

new Nullable<Double>()

Another way to get the same value in C# would be

default(Nullable<Double>)

In both cases, I don't know the syntax for Delphi. In the second case, I don't know whether something like this can be even represented there.

EDIT: Apparently, you can use the second version in Delphi, but not the equivalent of the first one. That's quite surprising to me.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Unfortunately I can't see how to do either in Delphi. `Nullable.Create(1.0)` (Delphi constructor syntax) works fine, but `Nullable.Create()` gives an error about no overload with that number of parameters, suggesting the default constructor isn't exposed :( – Tom Carver Oct 18 '11 at 14:46
  • update - sorry I was wrong, even Default(T) doesn't work in Delphi (it compiles, but is completely ignored at runtime, leaving depth with its previous value). – Tom Carver Oct 19 '11 at 09:26