Clodoaldo Neto Clodoaldo Neto - 2 months ago 11
C# Question

Convert nullable numeric into string

I want to convert a nullable numeric into a string maintaining the null value. This is what I'm doing:

int? i = null;
string s = i == null ? null : i.ToString();


Is there something shorter?

Answer

You could create an extension method for that:

public static string ToStringOrNull<T>(this Nullable<T> nullable) 
where T : struct {
  return nullable.HasValue ? nullable.ToString() : null;
}

Usage:

var s = i.ToStringOrNull();