Is there a simple way to check if value is null for every case?
rikki cattermole
rikki at cattermole.co.nz
Mon Aug 27 03:21:04 UTC 2018
On 27/08/2018 12:51 PM, SG wrote:
> On Sunday, 26 August 2018 at 16:39:53 UTC, rikki cattermole wrote:
>> UFCS function called isNull.
>>
>> e.g.
>>
>> import std.traits : isPointer;
>> bool isNull(T)(T value) if (is(T == class) || isPointer!T) {
>> return value is null;
>> }
>
> Hi Rikki,
>
> I'm still confused, I want to create a extension for checking null for
> every type, so in D I'll need to handle each case with Templates?
Templates make it the easiest way, since common patterns, like arrays,
classes and pointers have the exact same null check syntax.
> Because in C# I just need to compare an object/variable with null,
>
> x == null;
> myObject == null;
> myObject.i == null;
> myStruct == null;
> myStruct.j == null;
>
> This works fine in C#.
That code is only for classes. C# also has structs which are a value
type. Which it would not work for.
> But again, in D I'll need the check the type? Is possible to make one
> Template for all cases?
>
> The code below works, but I don't think this is a right thing to do, right?
You don't need isNull function for Nullable because it has a method
called it. That will be preferred (hence I specifically used isNull as
the name).
For Variant, use hasValue.
bool isNull(Variant value) {
return !value.hasValue;
}
Writing a Unified Function Call Syntax function isn't really an
extension. You're defining a function that is to be preferred when you
ask for a method of the same name. So that it appears as if it was
actually described as a method instead of a free-function (not attached
to class/interface/struct/union).
More information about the Digitalmars-d-learn
mailing list