Determine if a property of an anonymous type is a shared collection

I need a method to cycle through the properties of each object and register the property name and value. However, sometimes I end up in a property that is a list object and it all fails. I am collecting the condition below from various SO posts, but returns false every time. Would you like to know how to check if a property of a method is a generic collection type?

Class definition

public class DtccProducer
{
    public string ProducerDateOfBirth { get; set; }
    public string ProducerGender { get; set; }
    public string TransactionType { get; set; }
    public List<BigAddress> Addresses { get; set; }
    public List<BigCommunicationItem> Communications { get; set; }
}

      

Method

    private static void ParseProducer(object obj)
    {
        StringBuilder s = new StringBuilder();
        Type objType = obj.GetType();

        foreach (PropertyInfo info in objType.GetProperties())
        {
            string key = info.Name;

            Type propType = info.PropertyType;

            if (propType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(propType.GetGenericTypeDefinition()))
            {
                // This condition never passes - always evaluates to false
            }
            else
            {
                string value = (string) info.GetValue(obj, null);
                _sb.AppendLine(key + ": " + value);                    
            }
        }
    }

      

+3


source to share


1 answer


This is the code I am using to identify the lists in my log:

if (!propType.IsPrimitive && !propType.IsEnum && propType != typeof(string) && propType.GetInterfaces().Any(x => x.IsGenericType 
           && x.GetGenericTypeDefinition() == typeof(IEnumerable<>)))

      



Edit: I added some additional checks to filter out primitive types (int, bool, etc.), enum and strings.

+2


source







All Articles