C
C#2mo 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
HtmlCompiler
HtmlCompiler2mo ago
you could also use if (maybe.HasValue) {}
fæ
OP2mo ago
which do you prefer?
HtmlCompiler
HtmlCompiler2mo ago
i use all three tbh but mostly is int and .HasValue nowadays i believe
fæ
OP2mo ago
what about is not null
HtmlCompiler
HtmlCompiler2mo ago
really i use is not <type> rather
Joschi
Joschi2mo ago
There is one small reason for is over == and that is, that == could technically be overwritten. While is cannot.
huoyaoyuan
huoyaoyuan2mo ago
And also is {}, before is not null is a thing Actually I use ?? mostly, not explicitly checking for null
Angius
Angius2mo 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?