Using System.DateTime in a C# Lambda expression gives an exception
- by Samantha J
I tried to implement a suggestion that came up in another question: Stackoverflow question
Snippet here:
public static class StatusExtensions
{
public static IHtmlString StatusBox<TModel>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, RowInfo>> ex
)
{
var createdEx =
Expression.Lambda<Func<TModel, DateTime>>(
Expression.Property(ex.Body, "Created"),
ex.Parameters
);
var modifiedEx =
Expression.Lambda<Func<TModel, DateTime>>(
Expression.Property(ex.Body, "Modified"),
ex.Parameters
);
var a = "a" + helper.HiddenFor(createdEx) +
helper.HiddenFor(modifiedEx);
return new HtmlString(
"Some things here ..." +
helper.HiddenFor(createdEx) +
helper.HiddenFor(modifiedEx)
);
}
}
When implemented I am getting the following exception which I don't really understand. The exception points to the line starting with "var createdEx ="
System.ArgumentException was unhandled by user code
Message=Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type 'System.DateTime'
Source=System.Core
StackTrace:
Can anyone help me out and suggest what I could do to resolve the exception?