C#C
C#2y ago
sashok

Unable to get the FieldInfo's value

public static List<T> FindInstances<T>(object value)
{
    List<T> instances = new();

    Type type = value.GetType();

    foreach (FieldInfo field in type.GetFields())
    {
        if (typeof(T).IsAssignableFrom(field.FieldType))
        {
            object fieldValue = field.GetValue(value);

            if (fieldValue is T instance)
            {
                instances.Add(instance);
            }
        }
    }

    return instances;
}

The following method should find the fields of type
T
in the class.
When having these
strings
, it only returns a List of 2 empty ones.
public string string1 = "string 1";
public string string2 = "string 2";
Was this page helpful?