So I have, say, this type of method:
public ICollection<String> doSomething() { }
Currently, I’m trying to check if the return type of method is of type ICollection. However, in C#, I have to pass in a generic when I do the check. So I can’t do, say, “method is ICollection”.
The problem is that I don’t want to restrict the type of generic when I’m checking. In Java, I could just use a wildcard, but I can’t do that in C#. I’ve thought of trying to use the Type.GetGenericParamterContraints() and trying to stick the first result of it in ICollection’s generic constraint to check, but that also didn’t work. Anybody have any ideas?
isCollection(MethodInfo method){
Type[] ret = method.ReturnType.GetGenericParametersContraint();
Type a = ret[0];
return method.ReturnType is ICollection<a>;
}
EDIT: Added what I tried.
If it’s allowed to be the non-generic
System.Collections.ICollection(which is implemented byICollection<T>too) then it’s simply:If you only want to compare to generic
ICollection<T>(I see no reason to, but you may have your reasons):Note that that doesn’t work if the return type is non-generic. So it won’t work if there’s a class that implements
ICollection<T>but isn’t generic itself. Meaning it won’t catchclass Foo : ICollection<string>but it will catchclass Foo<T> : ICollection<T>.The first way will catch both just fine though.