Is there a simple way to check if value is null for every case?
vit
vit at vit.vit
Mon Aug 27 13:22:06 UTC 2018
On Monday, 27 August 2018 at 12:54:59 UTC, SG wrote:
> On Monday, 27 August 2018 at 03:21:04 UTC, rikki cattermole
> wrote:
>> Templates make it the easiest way, since common patterns, like
>> arrays, classes and pointers have the exact same null check
>> syntax.
>
> I see.
>
>> That code is only for classes. C# also has structs which are a
>> value type. Which it would not work for.
>
> The same thing for struct in C#
>
> Struct S{
> public int? i;
> }
>
> S.i == null; // This works nicely.
>
>> 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;
>> }
>
> The problem I'm trying to solve is beyond that. This is just an
> example. But bear with me, right now all I want is a function
> to check the value from 'a' type and return if it is null.
>
> The type could be a: Class, Struct, a Basic data type, Variant,
> Nullable and so.
>
> And what I see, these types has different behaviors, while in
> C# at least for this same case, I would write the same thing in
> few lines to perform it, in D I found very hard.
>
> Isn't counter intuitive the way D works? Because for each type
> Class/Nullable you check with .isNull, for Variant with
> .hasValue, for string (variable is null).
>
> Thanks.
hasValue isn't equivalent of isNull or is null. 'null' is valid
value in Variant:
import std.variant;
Variant v;
v = null;
assert(v.hasValue); //v has value
assert(v.get!(typeof(null)) is null); //value in v is
null
Nullable!T.isNull isn't equivalent of is null:
int* i = null;
Nullable!(int*) ni;
ni = i;
assert(ni.isNull == false); ///ni has value
assert(ni is null); ///ni value is null
string is null isn't equivalent of empty:
string str = "test";
str = str[0 .. 0];
assert(str !is null); ///str isn't null
assert(str.empty); ///str is empty
More information about the Digitalmars-d-learn
mailing list