How to parse a string into a nullable int in C#?

Parsing a string into a nullable int in C# allows you to handle cases where the string might not represent a valid integer. A nullable int (int?) can store either an integer value or null, making it ideal for scenarios where conversion might fail.

C# provides several approaches to parse strings into nullable integers, from extension methods to built-in parsing techniques that handle invalid input gracefully.

Syntax

Following is the syntax for declaring a nullable int −

int? nullableInt = null;
int? nullableInt = 42;

Following is the syntax for parsing using int.TryParse()

if (int.TryParse(stringValue, out int result)) {
   return result;
} else {
   return null;
}

Key Properties of Nullable Types

  • The HasValue property returns true if the variable contains a value, or false if it is null.

  • The Value property returns the actual value, but throws an InvalidOperationException if the value is null.

  • You can use == and != operators directly with nullable types.

  • Nullable types can only be used with value types, not reference types.

Using Extension Method for String to Nullable Int

An extension method provides a clean way to parse strings into nullable integers −

using System;

static class Program {
   static void Main(string[] args) {
      string s = "123";
      int? result = s.ToNullableInt();
      Console.WriteLine("Parsed value: " + result);
      
      string invalid = "abc";
      int? invalidResult = invalid.ToNullableInt();
      Console.WriteLine("Invalid string result: " + invalidResult);
   }
   
   static int? ToNullableInt(this string s) {
      if (int.TryParse(s, out int i)) 
         return i;
      return null;
   }
}

The output of the above code is −

Parsed value: 123
Invalid string result: 

Using Built-in TryParse Method

You can directly use int.TryParse() without creating an extension method −

using System;

class Program {
   static void Main() {
      string[] testStrings = {"42", "invalid", null, "0", "-15"};
      
      foreach (string str in testStrings) {
         int? parsed = ParseToNullableInt(str);
         Console.WriteLine($"Input: '{str}' -> Result: {(parsed.HasValue ? parsed.Value.ToString() : "null")}");
      }
   }
   
   static int? ParseToNullableInt(string input) {
      if (int.TryParse(input, out int result)) {
         return result;
      }
      return null;
   }
}

The output of the above code is −

Input: '42' -> Result: 42
Input: 'invalid' -> Result: null
Input: '' -> Result: null
Input: '0' -> Result: 0
Input: '-15' -> Result: -15

Handling Nullable Int Values

When working with nullable integers, you can check for values using HasValue property or null-coalescing operators −

using System;

class Program {
   static void Main() {
      string input = "456";
      int? nullableInt = ParseString(input);
      
      // Method 1: Using HasValue
      if (nullableInt.HasValue) {
         Console.WriteLine("Has value: " + nullableInt.Value);
      } else {
         Console.WriteLine("Value is null");
      }
      
      // Method 2: Using null-coalescing operator
      int defaultValue = nullableInt ?? -1;
      Console.WriteLine("Value with default: " + defaultValue);
      
      // Method 3: Direct comparison
      Console.WriteLine("Is null: " + (nullableInt == null));
   }
   
   static int? ParseString(string s) {
      return int.TryParse(s, out int result) ? result : (int?)null;
   }
}

The output of the above code is −

Has value: 456
Value with default: 456
Is null: False

Comparison of Parsing Methods

Method Advantages Use Case
Extension Method Clean, reusable, fluent syntax Frequent string-to-nullable parsing
Direct TryParse No additional methods, built-in One-time parsing operations
Ternary with TryParse Concise, inline conversion Simple conditional parsing

Conclusion

Parsing strings to nullable integers in C# provides robust error handling for invalid input. Use extension methods for frequent conversions, or int.TryParse() directly for simple cases. Always check HasValue or use null-coalescing operators when working with the results.

Updated on: 2026-03-17T07:04:36+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements