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