0

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

Venkat
  • 1,702
  • 2
  • 27
  • 47

1 Answers1

5

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.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • whats the difference between if(SegroupOf?.Contains("Team") == true) and if(SegroupOf?.Contains("Team")) – Venkat Jun 27 '23 at 11:35
  • @Venkat the latter doesn't compile, because `?Contains` returns a nullable `bool` , not a "normal" `bool`. – MakePeaceGreatAgain Jun 27 '23 at 11:36
  • It's worth pointing out that the code generated for `if (x?.Contains(y) == true)` is *significantly* longer than that generated for `if (x != null && x.Contains(y))`. This is rarely significant, but if you're calling this in a tight loop and performance is an issue, you should bear this in mind. – Matthew Watson Jun 27 '23 at 11:48
  • 1
    @MatthewWatson that's why I mentioned that in my last paragraph. Slightly and signifanctly are pretty opinion-based term, though. – MakePeaceGreatAgain Jun 27 '23 at 11:57
  • Actually yes, I take that back: I accidentally used `if(SegroupOf?.Contains("Team") is true)` rather than `if(SegroupOf?.Contains("Team") == true)` in my test - which of course does make a big difference, as [demonstrated here on sharp.io](https://sharplab.io/#v2:EYLgtghglgdgNAFxFANgHwAICYCMBYAKEIwGYACDHANgqzIBUBTAZwUIG9CzuLzKbgAe0EoGLBDgAUlAAwB+MswCUXHpwI9NFAOyK5AOgDCgmAmgxmkgERMIYK0rIBeJ2QQAnAK6MA3Ku4AvoT+vBTUZEIiYqxY0jjyiioaaiGaGLrMZACErjCeKKIAZIWKRiZmsJY2jHYOfsmBwQ2h/BHCokysJHEJyiHqWjzpemWm5lW29o5QmR7e9ZpBBEtAA) - so yes `== true` is fine! – Matthew Watson Jun 27 '23 at 13:08
  • In fact, looking at the assembler output from the jitter (on sharp.io) the two methods are pretty much identical in efficiency. – Matthew Watson Jun 27 '23 at 13:12