0

C#. I have the following classes:

public class SomeDerivedClass : SomeSuperClass 
{

}
public class Game  : SomeSuperClass 
{
    public List<SomeDerivedClass> inventory_changes = new List<SomeDerivedClass>();
}

public class SomeSuperClass
{
    public virtual void SomeMethod()
    {
        FieldInfo[] fields = GetType().GetFields();

        foreach (FieldInfo fieldInfo in fields)
        {
            if ((fieldInfo.FieldType.IsGenericType) && (fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.List<>)) && (fieldInfo.FieldType.GetGenericArguments()[0].IsSubclassOf(typeof(SomeSuperClass))))
            {
                List<SomeSuperClass> superclassList = fieldInfo.GetValue(this) as List<SomeSuperClass>;
                List<SomeDerivedClass> derivedClassList = fieldInfo.GetValue(this) as List<SomeDerivedClass>;

                Assert.IsNotNull(superclassList);
                Assert.IsNotNull(derivedClassList);

            }
        }
    }
}

If I instantiate the Game class, and call SomeMethod the following superclass asssertion would fail

Assert.IsNotNull(superclassList); //This fails

while the derived class asssertion would pass:

Assert.IsNotNull(derivedClassList); //This passes

I want to get that field as a list of the SuperClass, not the Derived class.

  • 1
    What are you trying to achieve? I assume `fields` is something like `this.GetType().GetFields()`? Why are you trying to use reflection? ... But this sounds like a variance problem https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance. – Jeremy Lakeman Jun 09 '23 at 01:20
  • If all derived classes of `SomeSuperClass` are supposed to have a list of some type, then use generics to enforce that rule `abstract class SomeSuperClass where T:SomeDataClass{ public List propertyName {get;set;}}`. Just because you can solve a problem via reflection, doesn't mean you should. – Jeremy Lakeman Jun 09 '23 at 01:23
  • A `List` is not a `List`. Suppose it was the case: you could add a `Game` to it, and the other code would receive an object which is not a `DerivedClass` which it was expecting. You need instead to use `List` or to use generic covariance along with an interface such as `IReadOnlyList` – Charlieface Jun 09 '23 at 01:47
  • Forgot to add FieldInfo[] fields = GetType().GetFields(); – SticksInGoo Jun 09 '23 at 12:49
  • What I'm trying to achieve is to have SomeMethod go through all variables that a derived class may have, and if those variables extend from SomeSuperClass, call a method on those objects. – SticksInGoo Jun 09 '23 at 14:57

0 Answers0