As others have stated you need to check for null before invoking ToString but to avoid repeating yourself you could create an extension method that does that, something like:
public static class DateTimeExtensions {
public static string ToStringOrDefault(this DateTime? source, string format, string defaultValue) {
if (source != null) {
return DateTime.Value.ToString(format);
}
else {
return String.IsNullOrEmpty(defaultValue) ? defaultValue : String.Empty;
}
}
public static string ToStringOrDefault(this DateTime? source, string format) {
ToStringOrDefault(source, format, null);
}
}
Which can be invoked like:
DateTime? dt = DateTime.Now;
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss");
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a");
dt = null;
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a") //outputs 'n/a'