I’m working with the System.Web.Helpers.WebGrid in an ASP.NET MVC 3 Razor project, and I’m having trouble understanding why the format parameter for a WebGridColumn is a Func<dynamic, object>.
If I create a column like this…
grid.Column(
format: x => string.Format("{0:d}", x.StartDate)
);
…I don’t get strong typing on the StartDate property. If I try to get around it like this…
grid.Column(
format: (MyObjectType x) => string.Format("{0:d}", x.StartDate)
);
…I’m told at runtime that my lambda can’t be cast to a Func<dynamic, object>. Is there some way I can use a non-dynamic lambda here? Even if it’s just <object, object>?
(I’m in .NET 4.0, and Func<in T, out TResult> is supposed to be contravariant on T, but I’m confused about how covariance and contravariance work with dynamic.)
As far as the type system is concerned,
dynamicis the same asobject.They cannot use a strongly-typed delegate because they don’t have a strongly-typed value to pass.
Inside
WebGrid, they get anObjectfrom aPropertyDescriptor, and pass that to your delegate.Covariance won’t help here; had
Func<YourType, string>been convertible toFunc<object, string>, it would be possible to call it with any other type and get an invalid cast.