I’m developing an application where I the need to invoke a method of a generic class and I don’t care about the instances actual type. Something like the following Java code:
public class Item<T>{ private T item; public doSomething(){...} } ... public void processItems(Item<?>[] items){ for(Item<?> item : items) item.doSomething(); }
At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it.
public interface IItem { void doSomething(); } public class Item<T> : IItem { private T item; public void doSomething(){...} } ... public void processItems(IItem[] items) { foreach(IItem item in items) item.doSomething(); }
This workaround works fine, but I’d like to know what is the correct way to achieve the same behavior.
EDIT:
I forgot to refer that the caller of processItems doesn’t know the actual types. Actually the idea was that the array passed as argument to processItems could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way.
The normal way to do this would be to make the method generic:
Assuming the caller knows the type, type inference should mean that they don’t have to explicitly specify it. For example:
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.