-1

Is it possible to access a struct's public members by their names / indices?

For example, if I have:

struct Person
{
  int id;
  string surname;
}

Person person;

Is it possible to get person.id with just the string "id" or the integer index 0? Or to get person.surname with the string "surname" or the integer index 1?

chie
  • 27
  • 1
  • 4
  • You can access a member by name using [reflection](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection). – itsme86 Aug 11 '20 at 20:46

1 Answers1

1

You can use reflection to get member by name (in this case field):

var p = new Person();
var fieldInfo = p.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine(fieldInfo.GetValue(p)); // prints 0
Guru Stron
  • 102,774
  • 10
  • 95
  • 132