names of variables in class as strings? reflection??

Let’s say I create a public class called People containing a number of variables in c#.

It might include say public string name = “default name”; and say public int id = 1; and say public string desc = “default description”; and so on.

Coming to that class without knowing the names of the variables, how could I:-

  • get a string value of the names of the variables (not their values) ie. ‘name’, ‘id’, ‘desc’ etc?

  • get a count of the number of public variables in the class?

  • even get the variable types of the variables in the class?

  • if the class was turned in to a list, get a string of the base class of the list ie. ‘People’?

Do I use reflection?

Could someone help me out with some example script?

Thanks in advance.

You could use reflection.

Type t = People.GetType();
foreach (var f in t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
    Debug.Log(f.Name);
}

This is an example the flags can be changed to get what you want.

Oh and don’t forget to add Using System.Reflection;

@Chris-Trueman ,

Many thanks for that!

Presume that above returns a string of the name of each variable in the class but if I change the flag it could return a string of the variable type? What is the significance of NonPublic in the above example?

Also if say I have a base class forming a list class, perhaps in a gameobject if that helps, how do I get a string of (without knowing it)

  • the base class?

  • the list class?

Finally, can I even usefully refer to a class through a string variable rather than directly?

The big question here is why you’d want to do this. Reflection is generally a tool for meta-programming, ie. programming tools that help you write programs, or for investigating other software or whatever - so instances where you don’t know what software you’re working with.

If you can access things directly instead of through reflection, you should do that. Reflection is slow, error-prone, and hard to debug. If you want to write code that you can use with a bunch of different classes, you should use interfaces or generics to describe the behaviour you’re looking for.

As for GetFields, it takes a bitmask set of arguments, which are detailed here. If you want to use it, you should really read the docs. Be aware that there’s also things like GetMethods, GetProperties, and so on. Finally, you can’t directly get private members of base classes - you’ll have to first find the base class, and then find the method or field.

Thanks Baste,

To answer your question, I’m looking at creating Playmaker actions to make my inventory lists, item classes etc more directly accessible through Playmaker…

Ah, so it does fall under the “meta-programming” category. So yes, this is a good usage of Reflection. :slight_smile:

In any case, assuming your code editor supports Intellisense (as MonoDevelop and Visual Studio both do, and seriously why would you use a code editor that doesn’t), just take the example code he posted, type “f.” in your editor, and scroll through the list and experiment. Most of the information available in there is self-explanatory, or if not, explanatory via a little experimentation. :slight_smile:

@StarManta ,

Thanks for the info. I’ll get experimenting… :wink:

Also, how would I change the value of a variable in a class using a string of the class name and a string of the variable name??? How would this work with a List?

You wouldn’t set it directly with strings.

If you look in my example, f is an object which can be cast to anything.

To get the value:

People person = new Person("John");
string firstName = (string)person.GetType().GetField("firstName",
            System.Reflection.BindingFlags.NonPublic |
            System.Reflection.BindingFlags.Instance).GetValue(person);

To set the value:

person.GetType().GetField("firstName",
            System.Reflection.BindingFlags.NonPublic |
            System.Reflection.BindingFlags.Instance).SetValue(person, "Dave");

The problem with this is you need to know the type to be able to cast it. I’m not too familiar with reflection to show an example of how this would work. Maybe someone can come in and show us both.

@ Chris Trueman,

Thanks - that really helps with my understanding. This Reflection stuff is really useful.

However, I am worried I am attempting the impossible in being able to drill down in to a list (by class name or variable name string after class name string) in to a variable (by string of name) and then in to the value to get or set.

It rather feels like diving too far underwater!

If it can be done, I could script actions for Playmaker that allowed people some massive freedom and communication with Lists - it would be revolutionary in Playmaker circles…

Check out this editor class. It basically will create a drop down list of components on a GameObject. Once you select a component, it will make a dropdown list of member variables. You can keep drilling down through member variables infinitely.

Check out the whole repo. It’s designed to do something very similar to what you want.

It has the potential to turn playmaker’s neat FSMs into complete piles of spaghetti. Use at your own risk.

@Chris-Trueman , et al,

I’ve tried similar code in Unity for class Items and it just isn’t working.

So my code:-

using UnityEngine;
using System.Collections;
using System.Reflection;

public class Items : MonoBehaviour {

    public int itemID;

    public string itemName;

    public string itemDesc;

    public float itemWeight;
}

and (and this script I attach to the main camera:-

using UnityEngine;
using System;
using System.Reflection;

public class ItemSearch : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Type t = Items.GetType();
        foreach (var f in t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
        {
            Debug.Log(f.Name);
        }
    }

    // Update is called once per frame
    void Update () {
   
    }
}

it just does not like it when I put ‘Items’ before ‘.GetType();’

Help…!

GetType is a method defined on objects. If you want to get a type directly, use typeof(Type):

Type t = typeof(Items)

You’re also asking for NonPublic fields, which won’t give you a lot of info, as the fields you have listed in Items are public.