-2

Consider we have model like:

class Person{
    public string Name{get; set;}
    public List<Contact> ContactInfo{get; set;}
 }

and Contact is like:

class Contact{
   public string Landline{get; set;}
   public string Mobile{get; set;}
}

I want to access ContactInfo(List<Contact>) and hence fetch values of Landline and Mobile using reflection in C#.

Seva
  • 1,631
  • 2
  • 18
  • 23
maverick6912
  • 108
  • 1
  • 10

2 Answers2

1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
        class Contact
        {
            public string Landline { get; set; }
            public string Mobile { get; set; }
        }

        class Person
        {
            public string Name { get; set; }
            public List<Contact> ContactInfo { get; set; }
        }

        static void Main(string[] args)
        {
            Person person = new Person();
            person.ContactInfo = new List<Contact>();
            person.ContactInfo.Add(new Contact { Landline = "123456", Mobile = "7654332"});

            PropertyInfo contactInfoPropertyInfo = person.GetType().GetProperty(nameof(Person.ContactInfo));
            List<Contact> contactInfoValue = contactInfoPropertyInfo.GetValue(person, null) as List<Contact>;
            Contact firstContact = contactInfoValue?.First();
            string landline = firstContact?.GetType().GetProperty(nameof(Contact.Landline))?.GetValue(firstContact, null) as string;
            string mobile = firstContact?.GetType().GetProperty(nameof(Contact.Mobile))?.GetValue(firstContact, null) as string;

            Console.WriteLine(landline);
            Console.WriteLine(mobile);
        }
    }
}
J.Hornik
  • 31
  • 3
1
 private static string GetReflectedLandlineValue(object person)
 {
      IEnumerable<object> contactList = (IEnumerable<object>)person.GetType().GetProperty("ContactInfo")?.GetValue(person);
      return (string) contactList.First().GetType().GetProperty("Landline")?.GetValue(contactList.First());
 }
MrVoid
  • 709
  • 5
  • 19
  • notice this is just to reflect the landline property from the first item of the collection , if you want to do this for each item of the collection you need to extract the part of the logic out. – MrVoid Dec 17 '18 at 14:36