Piotr P Piotr P - 3 months ago 26
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
{
[Key]
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:

"ID"
"Name"
"Address"


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

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.