© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
6 replies
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;
}
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
T
in the class.
When having these
strings
strings
, it only returns a
List
List
of 2 empty ones.
public string string1 = "string 1";
public string string2 = "string 2";
public string string1 = "string 1";
public string string2 = "string 2";
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Finding all FieldInfo's of BackingFields of a type
C#CC# / help
2y ago
❔ Unable to get automapper's projectTo() to work properly.
C#CC# / help
4y ago
Unable to calculate/store correct value to the db
C#CC# / help
2y ago
❔ Unable to box custom value type
C#CC# / help
3y ago