C# How do I get all the fields of a specific type from a derived class within the base class?

Viewed 844

I have a class that looks like this:

public abstract class NetBehaviour
{
    void setSyncFloat (SyncFloat[] values)
    {
        // Find all SyncFloat fields in the child 
        // class (the one that derived this class).

    }
}

How do I go about finding all the fields of a specific type in a class that derived from this class within this very class? It seems a bit tricky and I'm guessing I'll need reflections. Could anyone help me out?

2 Answers
public abstract class NetBehaviour
{
    void setSyncFloat (SyncFloat[] values)
    {
        // Find all SyncFloat fields in the child 
        // class (the one that derived this class).
        var fields = GetType()
            .GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
            .Where(fi => fi.FieldType == typeof(SyncFloat));
    }
}

BindingFlags have been included because I assume you want private fields.

Note that GetType() will get the runtime type i.e. the subclass type.

You are on the right track.
Gladly this in you class will also be of the derived type, enabling you to do this.GetType() to receive the explicit most derived Type of the object.
You can then use Type.GetFields() to receive an array of all fields of that type, that you can iterate.

Related