How to parse a string into a nullable int
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | static class Program { public static int? ToNullableInt(this string s) { int i; if (int.TryParse(s, out i)) return i; return null; } static void Main(string[] args) { string testString = ""; //NULL String int? testInt = ToNullableInt(testString); if(testInt == null) { Console.WriteLine("testInt is null"); } else { Console.WriteLine("testInt is null"); } Console.ReadLine(); } } |
Output:
1 2 3 | testInt is null |
