Home > Mobile >  Using iteration to show contents of fields in object c#
Using iteration to show contents of fields in object c#

Time:11-04

I'm in the process of learning the basics of C# and exploring some uses for the foreach loop. I have an object address, and was trying to iterate my way through it to show the contents of the various fields in the object. Below is the output i got when running the code, followed by expected output.

The output i got was:

System.String Building
System.String Street
System.String City
System.String Region

Expected output:

C5

London
Camden

Is this possible to do in a manner similar to the code below?

    class Address
    {
        public string? Building;
        public string? Street=string.Empty;
        public string? City=string.Empty;
        public string? Region=string.Empty;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Address address=new Address();
            address.Building="C5";
            address.Street=null;
            address.City="London";
            address.Region="Camden";  
            foreach (FieldInfo str in address.GetType().GetFields())
            {
                Console.WriteLine($"{str}");
            }
        }
    }

Thanks, Frank

CodePudding user response:

FieldInfo.GetValue(Object)

When overridden in a derived class, returns the value of a field supported by a given object.

foreach (var info in address.GetType().GetFields())
   Console.WriteLine($"{info.GetValue(address) ?? "Null"}");

Output

C5
Null // Added the null because... well ¯\_(ツ)_/¯
London
Camden

Notes

  • There are bunch of binding flags that you should familiarize yourself with when performing this type of reflection.
  • To stave off the next question, there is also Type.GetProperties
  • Reflection should only be used when there is no other way, 9 times out of 10 a problem can be solved without needing to invoke reflective methods, this becomes particularly important when working in hot paths, code maintenance, linking and tree shaking pre build optimizations
  •  Tags:  
  • c#
  • Related