What is the equivalent of Java wildcards in C# generics

The normal way to do this would be to make the method generic:

public void ProcessItems<T>(Item<T>[] items) {
  foreach(Item<T> item in items)
    item.DoSomething();
}

Assuming the caller knows the type, type inference should mean that they don’t have to explicitly specify it. For example:

Item<int> items = new Item<int>(); // And then populate...
processor.ProcessItems(items);

Having said that, creating a non-generic interface specifying the type-agnostic operations can be useful as well. It will very much depend on your exact use case.

Leave a Comment