Is there a way to infer the type of a second generic argument when it is the subtype of the first generic argument.
For example, given the following classes:
public interface IContainer<in TItem>
{
void Add(TItem item);
}
public class Container<TItem> : IContainer<TItem>
{
public void Add(TItem item)
{
// Add item to container.
}
}
We try the following code, showing one approach that works and one that does not:
public static class Program
{
public static void DoSomething<TContainer, TItem>(TItem item)
where TContainer : IContainer<TItem>, new()
{
var container = Activator.CreateInstance<TContainer>();
container.Add(item);
}
public static void Test()
{
// 1. Valid:
DoSomething<Container<int>, int>(5);
// 2. Not valid:
DoSomething<Container<int>>(5);
}
}
These types (int) must always be the same and that's validated by the constraint.
I'd argue this is different to the linked duplicate. This question asks about avoiding repeating the same type e.g. <T1<T2>,T2>
wheares the linked question asks about not specifying a type. The compiler can already validate with the constraint that each T2 must be the same.