I'm attempting to compare a transient object graph to an NHibernate-persisted object graph. Unfortunately my code breaks where properties of type IList<T>
are concerned. The code below works fine with instances of List<T>
, because List<T>
implements both IList<T>
AND IList
. Unfortunately, NHibernate's PersistentGenericBag only implements IList<T>
.
IList list1 = (IList)prop1.GetValue(object1, null);
IList list2 = (IList)prop2.GetValue(object2, null);
If either object1 or object2 is a PersistentGenericBag, I get an error such as:
System.Reflection.TargetInvocationException : Exception has been thrown
by the target of an invocation.
----> System.InvalidCastException : Unable to cast object of type
'NHibernate.Collection.Generic.PersistentGenericBag`1[MyNamespace.MyClass]'
to type 'System.Collections.Generic.List`1[MyNamespace.MyClass]'.
Is there a reliable way to retrieve the PersistentGenericBag instance as an IList<T> using reflection?
I had hoped the popular Compare .NET Objects class would help, but it fails with the exact same error.
Edit: All the answers below are on the right track. The problem was that the getter on the problematic IList<T>
property was attempting a cast to List<T>
, which obviously can't be done to a PersistentGenericBag. So, my fault for the misguided question.