Define explicit Nullable.Empty method to clearly assign "NO VALUE" to Nullable<T> types

Issue #347 closed
Zigmund Bulinsh created an issue

Hi!

Is this possible to add a static function to a Nullable record which will return a System.Variants.Null. This way we do not need to use System.Variants and it is also more explicit to read.

var
  x: Nullable<String>;
begin
  ...
  x := Nullable.Empty;
  { or }
  x := Nullable<String>.New; // which could return empty Nullable<String>
end.

Let me know what you think,

Thanks in advance, Stefan

BR,

ZB

Comments (5)

  1. Stefan Glienke repo owner

    No need to - in fact we had something like that until I implemented the possibility to do this:

    x := nil;
    

  2. Zigmund Bulinsh reporter

    Yes, but:

    var
      x: Nullable<TSomeClass>;
    begin
      x := TSomeClass.Create;
      X := nil;
      Writeln(x.HasValue);
    end;
    

    Will output TRUE. And this why we currently always use Null to assign “no value” and not nil.

    Some parts of our code has such a types… but I actually never used nullable for pointer/class types as they could be nil by themselves.

    Is that actually a best practice to not use Nullable<> for classes/pointers?

    As having Nullable<Pointer> allows for 3 states:

    • No value assigned (Unknown);
    • NIL pointer assigned;
    • Valid pointer.

  3. Stefan Glienke repo owner

    Nullable for reference types makes no sense imo because they already have the state of nil/null.

    The point of nullable is to amend the state of “no value” to value types that don’t have such state.

  4. Zigmund Bulinsh reporter

    Thanks for your time! I think I will push the refactoring of that part were our team were using Nullable for object reference as it really does not make sense and only adds another source of error.

    Best regards,

    ZB.

  5. Log in to comment