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?
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?
You can write some extension method:
public static string ToNullString(this int? i)
{
return i.HasValue ? i.ToString() : null;
}
Usage will be more simple:
string s = i.ToNullString();
Or generic version:
public static string ToNullString<T>(this Nullable<T> value)
where T : struct
{
if (value == null)
return null;
return value.ToString();
}
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();
UPDATE
Since C# 6, you can use the much more convenient null-conditional operator:
var s = i?.ToString();
I think
string s = i?.ToString();
is shorter.
I need formatProvider parameter for decimal type so removed generic version to specialize to decimal extension as below:
public static string ToStringOrNull(this Nullable<decimal> nullable, string format = null)
{
string resTmp = "";
if (nullable.HasValue)
{
if (format != null)
{
resTmp = nullable.Value.ToString(format);
}
else
{
resTmp = nullable.ToString();
}
}
else
{
resTmp = "";
}
return resTmp;
}