Elegant one-line way to use TryParse

I don’t know how about you, but for me using int.TryParse() always feel somehow not right, resulting in an ugly three lines of code to do just one operation:

int value;
if (!int.TryParse(valueToParseFromString, out value)
   value = 0;

If you are looking for cleaner code to satisfy your inner pedant you can use this one-line solution instead:

int value = int.TryParse(valueToParseFromString, out value) ? value : 0;

It will parse the valueToParseFromString and on success assign it to the value variable, otherwise it will return 0.

4 comments

comments user
TPAKTOPA

thank you, I use this construction:

.int value= int.TryParse(valueToParseFromString, out value) ? value: 0;.

comments user
DevD

This is still great, use it all the time! Only thing that’s changed that can make this one-liner more elegant is by removing the ‘int value’ declaration before the parse, add the ‘int’ datatype to the out variable ie:

if (!int.TryParse(valueToParseFromString, out int value)
value = 0;

//dostuffwithvaluenow

comments user
Brent

No longer required. Variable declaration can now be used within TryParse.

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables

comments user
Travis

I agree completely. Nice 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.