41

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 using Anonymous Types (var).

Rosmarine Popcorn
  • 10,515
  • 11
  • 56
  • 88

5 Answers5

72

Your question isn't perfectly clear. It sounds like you want the values of the fields for a given instance of your class:

var fieldValues = foo.GetType()
                     .GetFields()
                     .Select(field => field.GetValue(foo))
                     .ToList();

Note that fieldValues is List<object>. Here, foo is an existing instance of your class.

If you want public and non-public fields, you need to change the binding flags via

var bindingFlags = BindingFlags.Instance |
                   BindingFlags.NonPublic |
                   BindingFlags.Public;
var fieldValues = foo.GetType()
                     .GetFields(bindingFlags)
                     .Select(field => field.GetValue(foo))
                     .ToList();

If you merely want the names:

var fieldNames = typeof(Foo).GetFields()
                            .Select(field => field.Name)
                            .ToList();

Here, Foo is the name of your class.

jason
  • 228,647
  • 33
  • 413
  • 517
15

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);
}
Fredrik Mörk
  • 151,624
  • 28
  • 285
  • 338
7
myClass.GetType().GetProperties()
MrFox
  • 4,572
  • 4
  • 42
  • 76
3
var fields = whateverYourClassType.GetType().GetFields().Select(f => f.Name).ToList();
AJ.
  • 15,808
  • 20
  • 92
  • 148
2

Not quite the question asked - but here's how to get the values of all properties of type Decimal from an object called "inv":

var properties = inv.GetType().GetProperties();

foreach (var prop in properties)
{
    if (prop.ToString().ToLower().Contains("decimal"))
    {
        totalDecimal += (Decimal)prop.GetValue(inv, null);
    }
}
Graham Laight
  • 4,398
  • 3
  • 28
  • 27