Clodoaldo Neto Clodoaldo Neto - 1 year ago 87
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 Source

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;


var s = i.ToStringOrNull();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download