Danicco
Danicco

Reputation: 1673

C# get if a property is any sort of list

I'm trying to make a text writer according to my classes properties in the following pattern:

MyClass
    ID 1
    Name MyName
    AnotherProperty SomeValue
    ThisIsAnotherClass
        AnotherClassProperties 1

//Example class
public class MyClass
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string AnotherProperty { get; set; }
    public AnotherClass ThisIsAnotherClass { get; set; }
}

So I'm taking each property name, writing it, a blank space, then it's value (if there is any). Now I'm trying to implement support for lists and anything array-like for something like this:

MyClass
    ArrayTest
        1
        2
        3

If it's a class, I'll have a recursive for the function so I can display all values inside the list/array in this pattern. (it's for a webservice)

My question is, how can I find if a specific property is something list-able?

I've tried:

Type type = myObject.GetType();
PropertyInfo[] properties = type.GetProperties();
for(int i = 0; i < properties.Length; i++)
{
    if(properties[i].PropertyType.IsGeneric) //Possible List/Collection/Dictionary
    {
        //Here is my issue
        Type subType = properties[i].PropertyType.GetGenericTypeDefinition();
        bool isAssignable = subType.IsAssignableFrom(typeof(ICollection<>)); //Always false
        bool isSubclass = subType.IsSubclassOf(typeof(ICollection<>)); //Always false

        //How can I figure if it inherits ICollection/IEnumerable so I can use it's interface to loop through it's elements?
    }
    else if(properties[i].PropertyType.IsArray) //Array
    { 
    }
    else if(properties[i].PropertyType.IsClass && !properties[i].PropertyType.Equals(typeof(String)))
    {
        //Non-string Subclasses, recursive here
    }
    else
    {
        //Value types, write the text + value
    }
}

Upvotes: 0

Views: 125

Answers (1)

Bas
Bas

Reputation: 27115

Like mentioned in the comments: use Json as a way to format objects, it will save a lot of time.

If you have reason not to do this, you can check if the type is enumerable: This also covers the Type.IsArray case.

typeof(IEnumerable).IsAssignableFrom(properties[i].PropertyType)

As an added notice of caution: maybe you do not want to enumerate String and byte[] type objects.

Upvotes: 6

Related Questions