Is there a way to list all Variables (Fields) of a class in C#.
If yes than could someone give me some examples how to save them in a List and get them maybe us
This will list the names of all fields in a class (both public and non-public, both static and instance fields):
BindingFlags bindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static;
foreach (FieldInfo field in typeof(TheClass).GetFields(bindingFlags))
{
Console.WriteLine(field.Name);
}
If you want to get the fields based on some object instance instead, use GetType instead:
foreach (FieldInfo field in theObject.GetType().GetFields(bindingFlags))
{
Console.WriteLine(field.Name);
}