string conversion
nullable types
type casting
C# programming
data types

Convert string to nullable type int, double, etc...

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In C#, the safest way to convert a string into a nullable numeric type is usually a TryParse-based helper. That lets blank input become null and bad input fail gracefully without using exceptions as normal control flow.

Start With a Simple Nullable int

For a single type, the pattern is very small:

csharp
1using System;
2
3public static class ParseHelpers
4{
5    public static int? ToNullableInt(string? input)
6    {
7        if (string.IsNullOrWhiteSpace(input))
8            return null;
9
10        return int.TryParse(input, out var value) ? value : null;
11    }
12}
13
14Console.WriteLine(ParseHelpers.ToNullableInt("42"));
15Console.WriteLine(ParseHelpers.ToNullableInt(""));
16Console.WriteLine(ParseHelpers.ToNullableInt("abc"));

This gives you a clear policy:

  • blank or whitespace means null
  • valid number means parsed value
  • invalid text also means null

That is often exactly what you want for optional form fields, CSV imports, and query parameters.

The Same Pattern for double, decimal, and Others

You can repeat the same idea for other value types.

csharp
1using System;
2using System.Globalization;
3
4public static class ParseHelpers
5{
6    public static double? ToNullableDouble(string? input)
7    {
8        if (string.IsNullOrWhiteSpace(input))
9            return null;
10
11        return double.TryParse(
12            input,
13            NumberStyles.Float | NumberStyles.AllowThousands,
14            CultureInfo.InvariantCulture,
15            out var value
16        ) ? value : null;
17    }
18}
19
20Console.WriteLine(ParseHelpers.ToNullableDouble("3.14"));
21Console.WriteLine(ParseHelpers.ToNullableDouble(""));
22Console.WriteLine(ParseHelpers.ToNullableDouble("bad"));

The structure is the same. Only the parser changes.

Why TryParse Is Better Than Parse

You could write:

csharp
int? value = string.IsNullOrWhiteSpace(input) ? null : int.Parse(input);

But this throws an exception when the text is invalid.

Exceptions are useful for exceptional situations, not for expected bad input from users or external data. TryParse is better because:

  • it avoids exception-driven control flow
  • it is clearer for validation paths
  • it handles ordinary bad input cheaply and safely

In input-conversion code, TryParse is usually the right default.

A Reusable Generic Pattern

If you need the same behavior for many nullable structs, you can generalize it with a delegate-based helper:

csharp
1using System;
2
3public delegate bool TryParseHandler<T>(string s, out T value);
4
5public static class NullableParser
6{
7    public static T? ParseNullable<T>(string? input, TryParseHandler<T> parser)
8        where T : struct
9    {
10        if (string.IsNullOrWhiteSpace(input))
11            return null;
12
13        return parser(input, out var value) ? value : null;
14    }
15}
16
17int? i = NullableParser.ParseNullable("10", int.TryParse);
18double? d = NullableParser.ParseNullable("3.14", double.TryParse);
19
20Console.WriteLine($"{i} {d}");

This keeps the blank-to-null policy in one place.

Culture Matters for Floating-Point Parsing

For double and decimal, culture is a real issue. Some environments expect 3.14, others expect 3,14.

That means your parser needs a policy:

  • use invariant culture for machine-formatted input
  • use a specific local culture for user-entered regional values

If you ignore culture, numeric parsing may behave differently across servers or user environments.

For example:

csharp
1using System;
2using System.Globalization;
3
4decimal? value = decimal.TryParse(
5    "1234.56",
6    NumberStyles.Number,
7    CultureInfo.InvariantCulture,
8    out var parsed
9) ? parsed : null;
10
11Console.WriteLine(value);

This is much safer than relying on whatever the current process culture happens to be.

Parsing Is Not Business Validation

Converting a string to int? only answers “is this text a valid integer or blank?” It does not answer whether the value is acceptable for the business rule.

For example:

csharp
1int? quantity = ParseHelpers.ToNullableInt("-5");
2
3if (quantity is null)
4    throw new ArgumentException("Quantity is required.");
5
6if (quantity <= 0)
7    throw new ArgumentException("Quantity must be greater than zero.");

That separation is healthy:

  • parsing checks syntax
  • validation checks business meaning

Keeping those steps separate makes the code easier to test and reason about.

Common Pitfalls

The most common pitfall is using Parse and catching exceptions for ordinary invalid input. TryParse is the better tool.

Another mistake is returning 0 for blank or invalid text. That hides the difference between “missing” and “explicit zero.”

A third issue is ignoring culture when parsing floating-point types, which can produce subtle bugs across environments.

Finally, developers sometimes mix parsing and domain validation in one helper, which makes the conversion rules harder to reuse.

Summary

  • Use TryParse-based helpers to convert strings into nullable numeric types safely.
  • A common policy is blank string to null, valid number to parsed value, invalid text to null.
  • Use explicit culture settings for double and decimal parsing.
  • Keep parsing logic separate from business validation rules.
  • Reusable helpers make nullable conversion more consistent across the codebase.

Course illustration
Course illustration

All Rights Reserved.