Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# – contains throws null exception

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading