Benjamin RD
Benjamin RD

Reputation: 12044

Get specific type from List<CustomModel> using reflection

I have this part of the method:

var t = typeof(T);
var fieldValues = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var typesToCast = new List<string>();
var fieldsToCast = new List<string>();

foreach (var field in fieldValues)
{
    var attr = (MetaAttribute[])field.GetCustomAttributes(typeof(MetaAttribute), false);
    if (attr.Length > 0)
    {
        fieldsToCast.Add(field.Name.ToString());
        typesToCast.Add(field.PropertyType.Name);
    }
}

But, if I have a property like:

public MyModel something {get;set;}

The result of

field.PropertyType.Name

is MyModel

But, I have public List<MyModel> something {get;set;} how I can get the MyModel type using reflection for a List?

Upvotes: 1

Views: 34

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32063

What you are looking for is the first type argument of a type. You can get it with:

if (field.PropertyType.IsGenericType)
{
    var typeArguments = field.PropertyType.GetGenericArguments();
    typesToCast.Add(typeArguments[0].Name);
}
else
{
    typesToCast.Add(field.PropertyType.Name);
}

Upvotes: 1

Related Questions