C# Generic Type Inference... anyway to automatically infer the type of array elements?

Viewed 42

I'm building a MVC core IHtmlHelper extension to handle tables. Roughly speaking you provide the extension with an IEnumerable list of data records and a column layout and it produces an HTML table.

For the column layout I'd like some of the methods to be lambdas that accept a data record and return a value from it. For example for each row of the table the first column should contain such and such value from the data record.

So the MVC IHtmlHelper extension method will look like:

namespace TableStuff
{
    public class Column<T>
    {
        public Func<T, string> TDContent { get; set; }
        // ... plus any other settings needed
    }

    public static class Table
    {
        public static IHtmlContent BasicTable<T>(
            this IHtmlHelper htmlHelper,
            IEnumerable<T> Data,
            IEnumerable<Column<T>> Columns
            )
        {
            return new HtmlString("just a mockup");
        }       
    }
}

To use it you:

public class Test
{
    class ListEntry
    {
        public string Id { get; set; }
    }

    public void DefineTable()
    {
        // fake a couple of things to make example minimal
        IHtmlHelper t = null;
        var Data = new List<ListEntry>();

        // generate the table; in reality this would be a razor page via @Html.BasicTable(...)
        var c = t.BasicTable(Data, new [] {
            new Column<ListEntry> { TDContent = i => i.Id }
        });
    }
}

What I'm wondering is why "new Column< ListEntry > { ... }" has to specify an explicit type. I'd really rather have it just be ""new Column { ... }" and have the type inferred as ListEntry.

0 Answers
Related