Using System.DateTime in a C# Lambda expression gives an exception

Posted by Samantha J on Stack Overflow See other posts from Stack Overflow or by Samantha J
Published on 2011-11-19T01:44:09Z Indexed on 2011/11/19 1:51 UTC
Read the original article Hit count: 238

Filed under:

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?

© Stack Overflow or respective owner

Related posts about c#