Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the type contained within a (strongly typed) collection? [duplicate]

Tags:

c#

reflection

I have a class that looks like this :

public class ObjectA
{
    public ObjectB OneObject { get; set; }

    public List<ObjectC> ManyObject { get; set; }
}

And then a function to read what the class contains and return the type of property :

source = typeof(*some ObjectA*)

var classprops = source.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.PropertyType.IsClass && !x.PropertyType.IsValueType && x.PropertyType.Name != "String");

foreach (var prop in classprops)
{
    var classnamespace = CommonTool.GetNamespaceFromProp(prop);

    if ((prop.PropertyType).Namespace == "System.Collections.Generic")
    {
        string newprop = prop.ToString();
        int start = newprop.IndexOf("[")+1;
        int end = newprop.IndexOf("]");
        newprop = newprop.Substring(start, end-start);
        newprop = string.Format("{0}, Env.Project.Entites", newprop);
        classnamespace = newprop;
    }
    //some code to read attributes on the properties...
}

My problem is what is within the if ((prop.PropertyType).Namespace == "System.Collections.Generic"). It smells.

Any better way to do that?

edit :

A class in the application uses List<int>.
This caused crashes.
It wasn't only smelling bad.

like image 335
Kraz Avatar asked Oct 24 '25 06:10

Kraz


1 Answers

If you want to check if the property is a generic collection, and get the element type, you can check to see if it impelements IEnumerable<T> and get the type T if it does

Type propType = prop.PropertyType;
if (propType.IsGenericType)
{
    Type enumerableType = propType.GetInterfaces().FirstOrDefault(it => it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IEnumerable<>)));
    if(enumerableType != null)
    {
        Type elementType = enumerableType.GetGenericArguments()[0];
    }
}
like image 128
Lee Avatar answered Oct 26 '25 21:10

Lee