-1

With this definition

    public static HtmlTable<TRowModel> DisplayTable<TModel, TRows, TRowModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TRows>> expression, TRowModel rowModel = default(TRowModel)) where TRows : IEnumerable<TRowModel>
    {

        Func<TModel, TRows> deleg = expression.Compile();
        TRows result = deleg(helper.ViewData.Model);

        return new HtmlTable<TRowModel>(helper.ViewData.Model, result);
    }

i can call my extensions method like this

@(Html.DisplayTable(m => m.ListTest, new RowViewModel()).Render())

I would like to be able to explicitly specify only the TRowModel type so I can call my extension like so

@(Html.DisplayTable<RowViewModel>(m => m.ListTest).Render())

or, even better, like so

@(Html.DisplayTable(m => m.ListTest).Render())

where RowViewModel would be infered from the fact that I restricted my lambda parameter with where TRows : IEnumerable<TRowModel>

Is this possible in C#6 ? If not, what are my alternatives to avoid passing an empty object just so I don't have to specify explicitly every type in the diamond ?

Mathieu VIALES
  • 4,526
  • 3
  • 31
  • 48
  • 1
    If all generic types are inferrable from the parameters, then you can leave them all out. If not all types are inferrable, then you have to specify all of them (except for the `this` parameter). For more info, see this answer by the great Jon Skeet: https://stackoverflow.com/a/6878596/1220550 – Peter B Aug 01 '17 at 12:53
  • 1
    You can indeed infer the usage of generics, but if you start to specify these, you have to go to the end. It's either `DoSomething("foo", 1);` or `DoSomething("bar", 2);` Edit: @PeterB was faster than me. :(... ;) – Atlasmaybe Aug 01 '17 at 12:56
  • Thanks to both of you for. I now understand a bit more about generics. And i'm very displeased with that ... it means i'll have to keep this ugly, `new RowViewModel()` which, for a library, isn't very user-friendly nor beautiful. I guess there is no way for me to use the fact that `TRows` is forced to be an `IEnumerable` to use the `TRowModel` from `where TRows : IEnumerable` ? If this is possible, i would not go against the rule that you just gave me "either all or none"... – Mathieu VIALES Aug 01 '17 at 13:08

1 Answers1

0

Note: this post is only meant to let me tag this question as answered

Answer: In C#, when generics are involved they must ALL be specified explicitly except if they can ALL be inferred usage call. The this parameter is the only exception to this rule.

Thanks to @Peter B and @Atlasmaybe for your answers.

Mathieu VIALES
  • 4,526
  • 3
  • 31
  • 48