Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using iteration to show contents of fields in object c#

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading