0

I have a generic class...

public class SimilarityChooser<T, To>

...which has a constructor like this...

public SimilarityChooser(
  IEnumerable<T> entities,
  Func<T, string> getWord,
  Func<T, To> toOverview
)

...and I create a new instance of it like this...

var chooser = new SimilarityChooser<Customer, CustomerNameOverview>(
  CustomerRepository.GetAll(),
  c => c.Name,
  c => c.ToCustomerNameOverview()
);

...where the parameters fix the type parameter T to Customer and To to CustomerNameOverview.

I would have expected to be able to write the code without the type parameters...

var chooser = new SimilarityChooser(
  CustomerRepository.GetAll(),
  c => c.Name,
  c => c.ToCustomerNameOverview()
);

...but Visual Studio gives a compiler error Using the generic type 'SimilarityChooser' requires 2 type arguments

Why can't it infer the generic types, given that the arguments specify them?

EDIT So having read the answer @Shelby115 linked, I can see why this doesn't work for a constructor, but it seems it should work for a factory method. I made the ctor above private, and added the following...

public static SimilarityChooser<T, To> CreateMap(
  IEnumerable<T> entities,
  Func<T, string> getWord,
  Func<T, To> toOverview
) =>
  new SimilarityChooser<T, To>(entities, getWord, toOverview);

...but I still need the generic arguments. Why is this?

DreamingOfSleep
  • 1,208
  • 1
  • 11
  • 23
  • 1
    Perhaps this gives you some insight: https://stackoverflow.com/questions/8418087/why-cant-these-generic-types-be-inferred – Shelby115 Dec 27 '18 at 15:18
  • @Shelby115 Thanks for the link, much better quality answer than the one shown as a duplicate! – DreamingOfSleep Dec 27 '18 at 16:03
  • @Shelby115 Please see my edited question. I can't get tis to work with a factory method, which I thought should work even if the ctor doesn't – DreamingOfSleep Dec 27 '18 at 16:15
  • 1
    Your factory method cannot be inside of your generic type if you want to infer the types based on the method's parameters. Create a non-generic class (perhaps called SimilarityChooser) and put the factory method in there. – Grax32 Dec 28 '18 at 01:29
  • @Grax Thanks, that was it. I had the factory method in the generic class. All working now :) – DreamingOfSleep Dec 30 '18 at 15:14

0 Answers0