C
C#4d ago

Null check

if (maybe is int number)
{
Console.WriteLine($"The nullable int 'maybe' has the value {number}");
}
if (maybe is int number)
{
Console.WriteLine($"The nullable int 'maybe' has the value {number}");
}
VS
if(maybe != null)
{
Console.WriteLine($"The nullable int 'maybe' has the value {maybe}");
}
if(maybe != null)
{
Console.WriteLine($"The nullable int 'maybe' has the value {maybe}");
}
8 Replies
Omnissiah
Omnissiah4d ago
you could also use if (maybe.HasValue) {}
fæ
OP4d ago
which do you prefer?
Omnissiah
Omnissiah4d ago
i use all three tbh but mostly is int and .HasValue nowadays i believe
fæ
OP4d ago
what about is not null
Omnissiah
Omnissiah4d ago
really i use is not <type> rather
Joschi
Joschi4d ago
There is one small reason for is over == and that is, that == could technically be overwritten. While is cannot.
huoyaoyuan
huoyaoyuan4d ago
And also is {}, before is not null is a thing Actually I use ?? mostly, not explicitly checking for null
Angius
Angius4d ago
is {} over is not null lets you cast to a variable too x is {} y works, x is not null y does not
Want results from more Discord servers?
Add your server