C
C#3mo 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
FestivalDelGelato
you could also use if (maybe.HasValue) {}
fæ
OP3mo ago
which do you prefer?
FestivalDelGelato
i use all three tbh but mostly is int and .HasValue nowadays i believe
fæ
OP3mo ago
what about is not null
FestivalDelGelato
really i use is not <type> rather
Joschi
Joschi3mo ago
There is one small reason for is over == and that is, that == could technically be overwritten. While is cannot.
huoyaoyuan
huoyaoyuan3mo ago
And also is {}, before is not null is a thing Actually I use ?? mostly, not explicitly checking for null
Angius
Angius3mo ago
is {} over is not null lets you cast to a variable too x is {} y works, x is not null y does not

Did you find this page helpful?