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).
Asked
Active
Viewed 1e+01k times
45

Rosmarine Popcorn
- 10,761
- 11
- 59
- 89
-
2By "variables," do you mean fields, properties, or both? – AJ. Jun 30 '11 at 14:16
-
Fields ,sory i edited my post . – Rosmarine Popcorn Jun 30 '11 at 14:21
-
1_Show me the codez_... Here is the doc: http://msdn.microsoft.com/en-us/library/sa5z9w50.aspx – sehe Jun 30 '11 at 14:22
6 Answers
76
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
- 236,483
- 35
- 423
- 525
-
I get a "Expression cannot contain lambda expressions" with this syntax – pat capozzi Oct 30 '15 at 20:45
16
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
- 155,851
- 29
- 291
- 343
-
This worked for me. Was trying to get all the enums in my class: `MyEnum enum = (MyEnum)0;` – fat_flying_pigs Feb 17 '16 at 22:44
4
var fields = whateverYourClassType.GetType().GetFields().Select(f => f.Name).ToList();

AJ.
- 16,368
- 20
- 95
- 150
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,700
- 3
- 29
- 28
0
var fields = yourClass.GetType().GetProperties().Select(x => x.Name).ToList()

Lee Taylor
- 7,761
- 16
- 33
- 49

Xavier
- 87
- 1
- 4