Reflection

Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and PROPERTIES. If you are using attributes in your code, reflection enables you to access them.

Let’s take a simple example to understand it.

Create an Employee class with below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Reflection
{
    class Employee
    {

        private int _ID;
        public int ID{
            get { return _ID; }
            set { _ID = value; }
        }

        private string _Name;
        public string Name {
            get { return _Name; }
            set { _Name = value; }
        }

        public string Greeting() { 
            return "Hi " + Name;
        }
    }
}

Below is the sample code for console application

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

namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            
            //Get the current assembly.
            var assembly = Assembly.GetExecutingAssembly();
            Console.WriteLine(assembly.FullName);

            //Get all object in current assembly.
            var objects = assembly.GetTypes();
            foreach (var type in objects) {
                Console.WriteLine("Name: " + type.Name);

                //get all properties.
                var props = type.GetProperties();
                foreach (var prop in props) {
                    Console.WriteLine("Property Name: " + prop.Name + "\t Property Type: " + prop.PropertyType);
                }

                //get all methods
                var methods = type.GetMethods();
                foreach (var method in methods){
                    Console.WriteLine("Method Name: " + method.Name);
                }
            }

            Employee objEmployee = new Employee();
            objEmployee.ID = 1;
            objEmployee.Name = "Whitex";

            var objEmployeeType = typeof(Employee);

            //extract the Name property value from initialized object.
            var nameProperty = objEmployeeType.GetProperty("Name");
            Console.WriteLine("Property Value: " + nameProperty.GetValue(objEmployee,null));

            //invoke the method from initialized object.
            var GreetingMethod = objEmployeeType.GetMethod("Greeting");
            Console.WriteLine(GreetingMethod.Invoke(objEmployee,null));


            Console.ReadLine();
        }
    }
}
Advertisements

#reflection