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 one is done 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 on with all
I don't know if it was possible. Thanks for any help.
To get the names and types of each field in your class, you just need to use the operator
typeof
and a few other things.The examples that I will put now, make use of the class
System.Console
to display results on the screen.System.Type
it 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 to it so that you can do what you need in a simple way to understand:
Inside the function you want to use to print the members, you just need to do the following:
This will search for all the fields
public
,private
and that are notstatic
due to theBindingFlags
ones that I have put inside the function.The code above will output something like:
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:
In this method we only look for the properties of the class, whether
public
orprivate
and notstatic
, tested with the following class:It shows something like the following on the screen:
I hope it has helped you, here is a fiddle so you can see how it works :D