Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can this trim code ever fail?

Tags:

c#

I recently bumped into an exception in my code because I was trimming a null string. I replaced it with the following:

  SomeValue = (SomeString ?? "").Trim();

Can this code ever fail?

Thanks.

Note: I know I can add a try/catch; I'm just looking to make this line fail-proof without using a try/catch.

like image 983
frenchie Avatar asked Dec 30 '25 16:12

frenchie


1 Answers

This will not fail (ie. throw a NullReferenceException), assuming SomeString is indeed a string.

You could achieve the same in many ways:

SomeValue = (SomeString == null)?string.Empty:SomeString.Trim();
like image 177
Oded Avatar answered Jan 02 '26 04:01

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!