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,489
  • 14
  • 89
  • 151
RobouteGuiliman
  • 171
  • 3
  • 3
  • 9

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,286
  • 3
  • 22
  • 35
0

Reflection is your keyword. Try something like

typeof(Person).GetProperties();

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

CShark
  • 1,238
  • 15
  • 23
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
  • 52,021
  • 8
  • 71
  • 105
0

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

string nameOfField = nameof(Lastname);
Malte R
  • 412
  • 6
  • 15