Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all Variables of Class

Tags:

c#

reflection

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).

like image 648
Rosmarine Popcorn Avatar asked Jun 30 '11 14:06

Rosmarine Popcorn


People also ask

How do you find all variables in a class?

Field[] fields = YourClassName. class. getFields(); returns an array of all public variables of the class.

How do you display class variables in Python?

A class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.

How many variables are in a class?

There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.


2 Answers

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.

like image 149
jason Avatar answered Sep 25 '22 08:09

jason


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); } 
like image 34
Fredrik Mörk Avatar answered Sep 24 '22 08:09

Fredrik Mörk