How to parse a string into a nullable int to get either the int value of the string or null in C#

1 Answer

0 votes
using System;

static class Program
{
   static int? ToNullableInt(this string s) {
      int i;
      
      if (int.TryParse(s, out i)) 
        return i;
      
      return null;
   }
   static void Main() {
        string s = "4893";
      
        Console.WriteLine(s.ToNullableInt());
      
        s = "c#";
        Console.WriteLine(s.ToNullableInt());
      
        s = null;
        Console.WriteLine(s.ToNullableInt());
    }
}




/*
run:

4893



*/

 



answered Jun 7, 2021 by avibootz
...