C
C#6mo 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
Ꜳåąɐȁặⱥᴀᴬ
you could also use if (maybe.HasValue) {}
fæ
OP6mo ago
which do you prefer?
Ꜳåąɐȁặⱥᴀᴬ
i use all three tbh but mostly is int and .HasValue nowadays i believe
fæ
OP6mo ago
what about is not null
Ꜳåąɐȁặⱥᴀᴬ
really i use is not <type> rather
Joschi
Joschi6mo ago
There is one small reason for is over == and that is, that == could technically be overwritten. While is cannot.
huoyaoyuan
huoyaoyuan6mo ago
And also is {}, before is not null is a thing Actually I use ?? mostly, not explicitly checking for null
Angius
Angius6mo 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?