0

So I want to be able to get the fields of a class

public class Person
{
    public string Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

So I will to be able to get the public field names from a class, in this case I want a list of strings being {"Id", "Firstname", "Lastname"}

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
RobouteGuiliman
  • 191
  • 3
  • 3
  • 11

4 Answers4

4

You can use reflection to get properties or fields of a type:

var properties = typeof(Person)
                     .GetProperties()
                     .Select(p => p.Name)
                     .ToList();
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
0

Reflection is your keyword. Try something like

typeof(Person).GetProperties();

Then you can iterate over the result and get the names.

CShark
  • 1,413
  • 15
  • 25
0

You could make use of reflection.

var propertiesInfos = typeof(Person).GetProperties(BindingFlags.Public |
                                          BindingFlags.Static);
var propertieNames = string.Format("{{0}}",propertiesInfos.Select(prp=>prp.Name));
Christos
  • 53,228
  • 8
  • 76
  • 108
0

You could use nameof(..), and do it like this:

string nameOfField = nameof(Lastname);
Malte R
  • 468
  • 5
  • 16