programming
csharp
null-checking
tostring
code-practices

Checking for null before ToString

Master System Design with Codemia

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

Introduction

Calling ToString() on a non-null object is routine in C#, but calling it on null throws a NullReferenceException. That is why the right question is not “should I always call ToString()?” but “what value should my code produce when the object reference is missing?” Once that is clear, the implementation becomes straightforward.

Why null.ToString() Fails

ToString() is an instance method inherited from System.Object. Instance methods need an instance. If the variable contains no object reference, there is nothing to dispatch the method call to.

csharp
object value = null;
Console.WriteLine(value.ToString());

The code compiles, but it fails at runtime because value does not reference an object.

This matters in logging, UI formatting, CSV generation, and mapping code, where nullable values are common and the string conversion often sits on a hot path.

The Basic Null Check

The simplest safe pattern is still a plain conditional.

csharp
object value = GetValue();
string text = value != null ? value.ToString() : string.Empty;
Console.WriteLine(text);

This is explicit and easy to read. It also lets you choose what the fallback should be. The fallback does not have to be string.Empty. In some cases "(missing)", "N/A", or even null is more correct for the caller.

If the code is business-critical, the fallback value should reflect the meaning of missing data rather than just avoiding an exception.

Prefer the Null-Conditional Operator in Modern C#

C# offers a shorter form with the null-conditional operator.

csharp
object value = GetValue();
string text = value?.ToString() ?? string.Empty;
Console.WriteLine(text);

value?.ToString() returns null when value is null, and the null-coalescing operator ?? then supplies the default. This is usually the most idiomatic choice for application code because it is concise without being obscure.

The same idea works for nested access too:

csharp
string city = user?.Address?.City ?? "Unknown";

That pattern is often better than splitting the check into several separate if blocks.

Convert.ToString() Is Often the Easiest Option

Many developers miss the fact that Convert.ToString() already handles null safely.

csharp
object value = null;
string text = Convert.ToString(value);
Console.WriteLine(text == null ? "null result" : text);

For a null object reference, Convert.ToString(object) returns string.Empty. That makes it convenient when you only need a string and do not care about distinguishing null from empty output.

It is especially useful in data transformation code:

csharp
1object[] values = { 42, null, DateTime.Parse("2025-01-01") };
2
3foreach (object item in values)
4{
5    Console.WriteLine(Convert.ToString(item));
6}

This avoids repetitive null checks and keeps the loop readable.

Nullable Value Types Need Different Thinking

Nullable value types such as int? or DateTime? are not the same as plain object references, but the goal is similar: do not force a string conversion when no value exists.

csharp
int? count = null;
string text = count?.ToString() ?? "0";
Console.WriteLine(text);

Here the fallback is "0", which may or may not be semantically correct. If null means “unknown,” converting it to zero may hide missing data. The best fallback depends on what the receiving code expects.

Favor Intent Over Habit

In many codebases, the real improvement is not just adding a null check. It is removing unnecessary ToString() calls entirely. If you are using string interpolation, C# already formats many values safely.

csharp
object value = null;
Console.WriteLine($"Value: {value}");

This prints an empty slot after Value: instead of throwing. Likewise, structured logging libraries often accept objects directly and handle formatting later.

So before adding defensive string conversion everywhere, check whether a higher-level API already solves the problem more cleanly.

Common Pitfalls

  • Calling ToString() directly on a reference that may legitimately be null.
  • Using a fallback such as "0" or string.Empty when the business meaning of missing data is different.
  • Forgetting that Convert.ToString() already handles null safely for many cases.
  • Adding redundant ToString() calls inside string interpolation or logging APIs that already format values.
  • Treating nullable value types and nullable object references as if they always need the same fallback behavior.

Summary

  • 'ToString() is an instance method, so it fails when the reference is null.'
  • A plain conditional or ?. with ?? is the standard safe pattern in C#.
  • 'Convert.ToString() is a useful shortcut when empty string is an acceptable null result.'
  • Choose fallback values based on data meaning, not only on exception avoidance.
  • In some cases the best fix is to stop calling ToString() manually and let higher-level formatting APIs do the work.

Course illustration
Course illustration

All Rights Reserved.