1

Is there a way to check whether ParameterInfo is a Collection?

I have tried this:

ConstructorInfo[] constructorInfos = typeof(T).GetConstructors();
ConstructorInfo constructorInfo = constructorInfos[0];
ParameterInfo[] paramsVar = constructorInfo.GetParameters();
IEnumerable<ParameterInfo> collectionParams = paramsVar.Where(
    x => x.ParameterType.GetElementType() is ICollection);

but it does not work. Any ideas?

DevDave
  • 6,700
  • 12
  • 65
  • 99

2 Answers2

2

Check out the method Type.IsAssignableFrom:

ConstructorInfo[] constructorInfos = typeof(T).GetConstructors(); ConstructorInfo constructorInfo = constructorInfos[0]; ParameterInfo[] paramsVar = constructorInfo.GetParameters(); IEnumerable collectionParams = paramsVar.Where( x => x.ParameterType.GetElementType().IsAssignableFrom(typeof(ICollection)));

It's easy to confuse a.IsAssignableFrom(b) vs b.IsAssignableFrom(a)!

@BartoszKP has the right answer.

Community
  • 1
  • 1
allonhadaya
  • 1,297
  • 7
  • 19
2

Try this:

ConstructorInfo[] constructorInfos = typeof(T).GetConstructors();
ConstructorInfo constructorInfo = constructorInfos[0];
ParameterInfo[] paramsVar = constructorInfo.GetParameters();
IEnumerable<ParameterInfo> collectionParams = paramsVar.Where(
    x => typeof(ICollection).IsAssignableFrom(x.ParameterType));

(note that I've removed the GetElementType call and switched typeof(ICollection) and x.ParameterType)

BartoszKP
  • 34,786
  • 15
  • 102
  • 130