There are some scenarios when you extract a number from a text (it can be a text file or web page or etc…) and you need to convert it to a specific nullable type.

In this short post, I want to share a piece of code for converting a string to a nullable  int.




In ToNullableInt, I used a ternary operator to check if the string is convertible to int or not, and we can use the  TryParse method for that purpose, this method accepts a string and an out int parameters, and it returns a boolean to specify if the string converted or not. Then it puts the conversion result in the second parameter. So, if the number is convertible, ToNullableInt will return tempNumber as a nullable  int; otherwise, null is the returned value.