Search code examples
c#reflectioncastingnestedprivate

How to cast to a list of a type inaccessible due to protection level?


I have a type in a 3rd party library I can't mark as public but need to iterate through a list of these objects. I can get the object using reflection but this object is of a List. Simply casting it to List did not seem to work.

Type pType = typeof(PublicType).GetNestedTypes(BindingFlags.NonPublic).First();//gets correct NestedPrivateType, not sure if i can use this to help me cast
object listObj = typeof(PublicType).GetField("_theList", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(publicTypeObj);//this gets the list of objects that are of the nested private type
List<object> theList = (List<object>)listObj;//exception, unable to cast

I casted the object to List and I expected it to cast properly.


Solution

  • For your example:

    object listObj = typeof(PublicType).GetField("_theList", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(publicTypeObj);
    

    To enumerate through listObj you can cast it to IEnumerable and use it with foreach loop:

    IEnumerable theEnumerable = (IEnumerable)listObj;
    foreach (var item in theEnumerable) { ... }