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?