My code
string? SegroupOf;
if(SegroupOf.Contains("Team"))
{
}
If SegroupOf is null it throws an error. How to handle null? I have given SegroupOf as nullable, how to make sure even if its null it doesnot throw any error
My code
string? SegroupOf;
if(SegroupOf.Contains("Team"))
{
}
If SegroupOf is null it throws an error. How to handle null? I have given SegroupOf as nullable, how to make sure even if its null it doesnot throw any error
You can use the null-conditional-operator like so:
if(SegroupOf?.Contains("Team") == true)
However as SegroupOf?.Contains
returns a bool?
instead of bool
, you need to compare the result to the bool
-value true
.
You can also just use old-school null-check:
if(Segroup != null && Segroup.Contains("Team"))
However that is slightly different as the null-conditional is short-circuiting, meaning Segroup
is only accessed once, while in the second case it's accessed two times.