We don't have nullable types in FPC?
With FPC 3.2.1 and newer:
program tnull;
{$mode objfpc}{$H+}
uses
Nullable;
procedure Test;
var
n: specialize TNullable<LongInt>;
begin
Writeln(n.HasValue);
n := 42;
Writeln(n.HasValue);
Writeln(LongInt(n));
n.Clear;
Writeln(n.HasValue);
end;
begin
Test;
end.
Output:
FALSE
TRUE
42
FALSE
But the problem remains because if V was not initialized, the result of VarIsNull(V) will be false (because initialized with random):
Not quite right. Like e.g.
AnsiString and dynamic arrays a
Variant is a managed type. Thus it's initialized by the compiler/RTL to a default value which (as you noticed) is
not Null, but
Unassigned. You can test for it with
VarIsEmpty which will return
True for such a
Variant.
How can I test if a variable has a valid instance of an object if the opposite of nil is not always assigned?
In my code, I can follow my rule of always initialising to nil, but how can I test that if I'm handed something from a black box of someone else's code?
You can't, because to decide whether some variable (especially pointer types like classes, dynamic arrays and such) is a valid, correct "instance" of its type is essentially uncomputable at least in languages that don't run on some kind of VM (e.g. Java, .Net, JavaScript) and thus have more control over things.
So the conclusion should be: could it be possible to envisage a new function ?:
isinitialized(myvariable)
Such a function only makes sense for local variables (due to the above point of computability) and only inside the same function and
then you don't need this anymore, because you're in control of your own code, thus you know whether you initialized it or not.