Get all the names of properties of a class,Getting property names of a class in unity

I created this class called Genes and I want to get all it’s properties inside of another script. I tried using

PropertyInfo[] props = typeof(Genes).GetProperties();

but props is an empty array. This is my class Genes:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Genes {
    private float size;
    private float speed;
    private float probability;
    private int color;

    public Genes(float size, float speed, float probability, int color) {
       this.size = size; 
       this.speed = speed; 
       this.probability = probability; 
       this.color = color; 
    }
}

and I basically want to run over size, speed, probability and color using a foreach loop. What is the problem?

A property in the .NET / Mono framework is something different from a field. Your class doesn’t contain any properties, only fields. So you have to use GetFields instead of GetProperties. Also get get back FieldInfo objects.

edit
I forgot to mention since your fields are private you have to use proper BindingFlags wheh using GetFields. GetFields / GetProperties without any parameters only return public and nonstatic members by default.

In most cases reflection is not the way to go. It’s not really clear what you want to achieve here. The number of fields is hardcoded in the class. So you can just directly access them. Reflection should only be used when the actual class is not known. This is often the case when you create a general purpose serialization system. Be aware that reflection is slow and produces a lot of garbage. Also it has to be handled correctly. Reflection generally works with “object” values so you most likely have to cast the value to the right type.

Without more information we can’t help you any further.