Reputation: 187
My ProcessDate type is DateTime?
when i use ToString it is showing that exception.
dfCalPlanDate.Text = concreteCalPlan.ProcessDate.ToString("d");
Thank you for your interested.
Upvotes: 4
Views: 3256
Reputation: 172380
Simple: Nullable<T>
(and, thus, Nullable<DateTime>
, aka DateTime?
) does not have a method ToString(String)
.
You probably wanted to invoke DateTime.ToString(String)
. To do this in a null-safe way, you can use C# 6's null-conditional operator ?.
:
dfCalPlanDate.Text = concreteCalPlan.ProcessDate?.ToString("d");
which is a concise way of writing:
var date = concreteCalPlan.ProcessDate;
dfCalPlanDate.Text = (date == null ? null : date.Value.ToString("d"));
Note that this will yield null
if ProcessDate
is null
. You can append the null-coalescing operator ??
if you need another result in that case:
dfCalPlanDate.Text = concreteCalPlan.ProcessDate?.ToString("d") ?? "no date set";
Upvotes: 13
Reputation: 6292
ProcessDate is not a DateTime. ProcessDate.Value is. You need to do:
dfCalPlanDate.Text = concreteCalPlan.ProcessDate.Value.ToString("d");
Remember to check if the DateTime? has a value first.
Upvotes: 3