Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through class fields and print them

Tags:

c#

If I have for example one class like

public class User{             public int Id { get; set; }             public int Reputation { get; set; }             public string DisplayName { get; set; }             public DateTime LastAccessDate { get; set; }             public DateTime CreationDate { get; set; }             public string WebSiteUrl { get; set; }             public int Views { get; set; }             public int Age { get; set; }             public int UpVotes { get; set; }             public int downVotes { get; set; }             public string Location { get; set; }             public string AboutMe { get; set; }     } 

And I want to iterate through these fields dynamicly, for example to some method which will inspect passed object and it will return to caller its fields.

Is this possible ?

like image 669
BobRock Avatar asked Jul 19 '11 09:07

BobRock


1 Answers

They're not fields, they're properties. You can use reflection to list them:

User user = ... foreach(PropertyInfo prop in typeof(User).GetProperties()) {     Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(user, null)); } 
like image 108
Thomas Levesque Avatar answered Sep 23 '22 06:09

Thomas Levesque