.NET – izabelawlodarska.com https://izabelawlodarska.com Follow me for architecture, .net, sitecore and software engineering tips Wed, 02 Jan 2019 19:57:10 +0000 en-GB hourly 1 https://wordpress.org/?v=6.9.4 https://i0.wp.com/izabelawlodarska.com/wp-content/uploads/2023/01/cropped-android-chrome-512x512-1-1.png?fit=32%2C32&ssl=1 .NET – izabelawlodarska.com https://izabelawlodarska.com 32 32 122590972 Elegant one-line way to use TryParse https://izabelawlodarska.com/2018/04/15/elegant-one-line-way-to-use-tryparse/#utm_source=rss&utm_medium=rss&utm_campaign=elegant-one-line-way-to-use-tryparse https://izabelawlodarska.com/2018/04/15/elegant-one-line-way-to-use-tryparse/#comments Sun, 15 Apr 2018 18:31:35 +0000 http://www.izabelawlodarska.com/?p=225 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.

]]>
https://izabelawlodarska.com/2018/04/15/elegant-one-line-way-to-use-tryparse/feed/ 4 225