web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :

Reflection, retrieve property type

Michael Ghebremedin Profile Picture Michael Ghebremedin 107

    Defining classes

    public class Address
    {
        public string Steet { getset; }
        public string Apartment { getset; }
        public string City { getset; }
        public string State { getset; }
    }
    public class Car
    {
        public string Make { getset; }
        public int Year { getset; }
        public string Made { getset; }
    }
    public class Person
    {
        public string FirstName { getset; }
        public string LastName { getset; }
    }
    public class PersonalInfo
    {
        public Car MyCar { getset; }
        public Address MyAddress { getset; }
        public Person MyInfo { getset; }
    }

Here we will create an instance of PersonalInfo, from this instance we will retrieve property information.
   class Program
    {
        static void Main(string[] args)
        {
            PersonalInfo info = new PersonalInfo();
            
            Type pi = info.GetType();
            PropertyInfo[] myPropertyInfo = pi.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            DisplayPropertyInfo(myPropertyInfo);
            Console.WriteLine(pi.Name);
            Console.Read();
        }

        public static void DisplayPropertyInfo(PropertyInfo[] myPropertyInfo)
        {
            // Display information for all properties.
            for (int i = 0; i < myPropertyInfo.Length; i++)
            {
                PropertyInfo myPropInfo = (PropertyInfo)myPropertyInfo[i];
                Console.WriteLine("The property name is {0}.", myPropInfo.Name);
                Console.WriteLine("The property type is {0}.", myPropInfo.PropertyType);
            }
        }
    }

Output:
The property name is MyCar.
The property type is ClassLibrary1.Car.
The property name is MyAddress.
The property type is ClassLibrary1.Address.
The property name is MyInfo.
The property type is ClassLibrary1.Person.
PersonalInfo


This was originally posted here.

Comments

*This post is locked for comments