0

I would like to know if there is a way to determine all variables in an argument type, with all their extensions.

For example if I have something called Kitten

Theres Kitten.Name, Kitten.Age Kitten.Type etc.

How do I access all kitten things without knowing them and have them print llke this

"Kitten.Name = Max, Kitten.Age = 4, Kitten.Type = Siamese, Kitten.Owner = Sara"

In this case I didn't know Sara was the owner, but now I know because I asked for all Kitten properties.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
ali.vic
  • 11
  • 4
  • 6
    Reflection! Look at [Type.GetProperties()](https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=netcore-3.1). – itsme86 Jun 25 '20 at 17:08
  • If you want all of the data for printing purposes, don't manually loop over the properties with reflection, although that will work. Use a serializer...serializers are perfect for taking an object structure and converting it into a format that you can easily consume elsewhere. – David L Jun 25 '20 at 17:10
  • How do I serialize them? – ali.vic Jun 25 '20 at 17:11

1 Answers1

0

Like @itsme86 has already mentioned... With reflection.


  foreach (PropertyInfo item in userInfo
                .GetType()
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead))
            {
                Console.WriteLine($"{item.Name}: {item.GetValue(userInfo, null)}");
            }
Legacy Code
  • 650
  • 6
  • 10