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.

static void Main(string[] args)
{
  Console.Write("please enter your age: ");
  var age = Console.ReadLine();

  Console.WriteLine($"your age ten years from now: {ToNullableInt(age)+10}");
}

 

static int? ToNullableInt(string number)
{
  int tempNumber;
  return (int.TryParse(number.Trim(), out tempNumber) ?
  tempNumber as int? : null);
}

 

 

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.