The best way to make a collection of types and check against it

How can I create a collection that can store a data type (e.g. string, datetime, decimal, etc.)? and who use this collection to compare as such:

if (pi.PropertyType.IsIn ([how can check against the collection of type) //where pi is a property info]))
{

}

any suggestions?

+3
source share
2 answers
List<Type> types = new List<Type> {typeof(string), typeof(int)};
if (types.Contains(pi.PropertyType))
{
  //do stuff
}
+3
source

I hope I understand your question correctly. First, a more precise definition of the type of collection is required. Here is what I will use:

  • Collections are shared

  • Collections implement one of the standard collection interfaces, such as IList<T>, ICollection<T>or IEnumerable<T>. In this example, the type of the collection is the type obtained from IEnumerable<T>.

, , , GetInterfaces(), , IsGenericType, (.. IList<String> IList<>) GetGenericTypeDefinition():

var genericCollectionType = typeof(IEnumerable<>);
var isCollection = pi
  .PropertyType
  .GetInterfaces()
  .Where(type => type.IsGenericType)
  .Select(type => type.GetGenericTypeDefinition())
  .Contains(genericCollectionType);
if (isCollection) {
  ...
}
0

All Articles