Stijn Van Antwerpen
Stijn Van Antwerpen

Reputation: 1986

initialize an IEnumerable property using reflection in c# (propertyInfo)

Assuming a class (could be others)

class Foo()
{
     IEnumerable<int> SomeNumbers { get; set; }
     IEnumerable<string> SomeStrings { get; set; }       
     int[] ArrayOfInt { get; set; }
     List<int> AListOfIntegers { get; set; }
}

And a method

void Initialize(object obj)
{
     var props = obj.getType().GetProperties();
     foreach(var prop in props)
     {
         //Some logic in case property is a single value, this is using:
         //Convert.ChangeType(value, property.PropertyType, null)

         var list = //Do Some Magic
         prop.SetValue(obj, list, null);
     }
}

How to create a list of the right type?

I tried:

var list = property.PropertyType.GetConstructor(new CType[0]).Invoke(new object[0]);

But this don't work since IEnumerable does n't have constructors (it is an interface), but any supertype would be fine here.

var list = Enumerable.Empty<property.PropertyType.MemberType>();

Isn't even legal

Upvotes: 2

Views: 3777

Answers (1)

Andrey Tretyak
Andrey Tretyak

Reputation: 3231

You can create instance of List<T> that inherints IEnumerable<T> with this code:

var genericType = property.PropertyType.GetGenericArguments().First();     
var instance = Activator.CreateInstance(typeof(List<>).MakeGenericType(genericType));

Resulted instance could be set as property value.

prop.SetValue(obj, instance, null);

Also you can create empty Enumerable<T> using this code:

var genericType = property.PropertyType.GetGenericArguments().First();             
var method = typeof(Enumerable).GetMethod("Empty").MakeGenericMethod(genericType);
var emptyEnumerable = method.Invoke(null, null); 

Upvotes: 6

Related Questions