How to loop through attributes of a class in C#?

Question:

I have several classes with different attributes, one of them for example is:

class MGestion
{
    public int age { get; set; }
    public String gestion { get; set; }
    public String inicio { get; set; }
    public String fin { get; set; }
    public String descripcion { get; set; }
    public MGestion(int a,String g,String i,String f,String d) {
        age = a;
        gestion = g;
        inicio = i;
        fin = f;
        descripcion = d;
    }
}

What I want to do is be able to iterate through these attributes like an array and get the name and data type of each of them.

That is to say something like this:

name: age, data type : int
name: management, data type : String
.. and so with everyone

I don't know if it was possible. Thanks for any help.

Answer:

To get the names and types of each field in your class, you just need to use the typeof operator and a few other things.

The examples that I will present now make use of the System.Console class to display results on the screen.

System.Type only stores information about the type it belongs to, i.e. its own class.

Method 1: Get names and types of the fields in a class.

Now, let's assume with the class that you have given us in the example, I have made some modifications so that you can do what you need in the simple way to understand:

public class MGestion
{
    public int age;
    public String gestion;
    public String inicio;
    public String fin;
    public String descripcion;
}

Inside the function you want to use to print the members, you just need to do the following:

using System;
using System.Reflection;

// Namespace, class Program, class MGestion, etc...
public static void Main()
{
    Type Datos = typeof (MGestion);
    Console.WriteLine("Los campos de la clase '" + Datos.Name + "', son:");
    foreach (FieldInfo F 
         in Datos.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) // Aqui ocurre la magia :)
    {
        Console.WriteLine("Nombre: '{0,-12}', Tipo: '{1,-10}'", F.Name, F.FieldType.Name);
    }
}

This will search for all public , private , and non- static fields due to the BindingFlags I've put inside the function.

The code above will output something like:

Los campos de la clase 'MGestion', son:
Nombre: 'age         ', Tipo: 'Int32     '
Nombre: 'gestion     ', Tipo: 'String    '
Nombre: 'inicio      ', Tipo: 'String    '
Nombre: 'fin         ', Tipo: 'String    '
Nombre: 'descripcion ', Tipo: 'String    '

Method 2: Get names and types of properties in a class.

As we well know, the fields and the properties are two different things, mysteriously, the properties are also variables, but more beautiful and that.

To get the list of properties and print their value, we simply have to change two things to the form we used above so that it looks like this:

foreach (PropertyInfo F 
     in Datos.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) // Aqui ocurre la magia :)
{
    Console.WriteLine("Nombre: '{0,-12}', Tipo: '{1,-10}'", F.Name, F.PropertyType);
}

In this method we only look for the properties of the class, whether they are public or private and that are not static , tested with the following class:

public class MGestion
{
    public int age { get; set; }
    public String gestion { get; set; } 
    public String inicio { get; set; } 
    public String fin { get; set; } 
    public String descripcion { get; set; } 
    private int x { get; set; } 
    public int a;
    public int b;
    public string c;
}

It shows something like the following on the screen:

Los campos de la clase 'MGestion', son:
Nombre: 'a           ', Tipo: 'Int32     '
Nombre: 'b           ', Tipo: 'Int32     '
Nombre: 'c           ', Tipo: 'String    '

Las propiedades de la clase 'MGestion' son:
Nombre: 'age         ', Tipo: 'System.Int32'
Nombre: 'gestion     ', Tipo: 'System.String'
Nombre: 'inicio      ', Tipo: 'System.String'
Nombre: 'fin         ', Tipo: 'System.String'
Nombre: 'descripcion ', Tipo: 'System.String'
Nombre: 'x           ', Tipo: 'System.Int32'

I hope it has helped you, here is a fiddle so you can see how it works 😀

Scroll to Top