Piotr P Piotr P - 11 months ago 60
C# Question

Getting list of class fields

I am trying to create a generic method for my search, but I don't know how to return list of fields from my class.

Let's say I've got a class:

public class Table
public int ID { get; set; }

public string Name { get; set; }

public string Address { get; set; }

And now I want to return a list that would look like this:


How do I do that?

tried something like this:

FieldInfo[] fields = typeof(T).GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
string[] names = Array.ConvertAll<FieldInfo, string>(fields,
delegate(FieldInfo field) { return field.Name; });

But it has some unnecessary text after field names

Answer Source

You can do this with reflection

var listOfFieldNames = typeof(Table).GetProperties().Select(f => f.Name).ToList();

Note that you obviously want the properties, not the fields. The term "fields" refers to the private (instance) members. The public getters/setters are called properties.