-1

I try fill property type of ICollection<Person> or ICollection<T> .I give an objectList type of List<object> or ICollection<object> anyway i can't set value property type of ICollection<Person> by list of object

if (property.PropertyType.IsGenericType &&
     property.PropertyType.GetGenericTypeDefinition()
       == typeof(ICollection<>))
   {

      Type itemType = property.PropertyType.GetGenericArguments()[0];
      ICollection<object> objectList =GetObjectList();
      property.SetValue(item, objectList);


   }

thanks.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Amir Movahedi
  • 1,802
  • 3
  • 29
  • 52

2 Answers2

1

You can't set an ICollection<Person> to an ICollection<object> since ICollection isn't contravariant (there is no in keyword in the generic parameter declaration).

You will explicitly have to cast the collection of object to Person

if (property.PropertyType.IsGenericType &&
 property.PropertyType.GetGenericTypeDefinition()
   == typeof(ICollection<>))
{
  Type itemType = property.PropertyType.GetGenericArguments()[0];
  ICollection<Person> objectList =GetObjectList().Cast<ICollection<Person>>();
  property.SetValue(item, objectList);
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

Your solution is LINQ, use method OfType or Cast to cast or select objects of specified type. Since you may not convert the ICollection<object> to ICollection<Person> directly but you have a workaround to achieve the same.

ICollection<Person> objectList = GetObjectList().OfType<Person>().ToList();

or

ICollection<Person> objectList = GetObjectList().Cast<Person>().ToList();

This piece of code would return you a List<Person> and since List<T> implements ICollection<T> which means ICollection<Person> here so result will be assignable to your property

in most cases Cast() perform faster then OfType() as there is additional a type check is involved in OfType. read this for more info When to use Cast() and Oftype() in Linq

Update

  object objectList = GetObjectList();
  property.SetValue(item, Convert.ChangeType(objectList, property.PropertyType));

this will convert the value if the types are compatible. this example does not require you to know the underlying type. read more about ChangeType http://msdn.microsoft.com/en-us/library/dtb69x08.aspx

Community
  • 1
  • 1
pushpraj
  • 13,458
  • 3
  • 33
  • 50