19 Jun

C# All Need To Know About Reflection

Reflection is the ability of a managed code to read its own metadata at runtime. .NET Framework allows us the type information. For example, we can learn to the method names of a given type in C#. To do this, we use the “GetMethods” method in System.Type class.

    /// 
    /// Sample class
    /// 
    public class ReflectionExample
    {
        public void SampleMethod1(string message)
        {
            Console.WriteLine("My name is SampleMethod1");
            Console.WriteLine("Your message is " + message);
        }

        public void SampleMethod2(int id)
        {
            Console.WriteLine("My name is SampleMethod2");
            Console.WriteLine("Your id is " + id.ToString());
        }
    }

Usage:

            MethodInfo[] allMethods = typeof(ReflectionExample).GetMethods();
            foreach (MethodInfo method in allMethods)
            {
                Console.WriteLine("MethodName=" + method.Name + " "+
                                  "IsPublic=" + method.IsPublic.ToString());
            }

            //Output:
            //MethodName=SampleMethod1 IsPublic=True
            //MethodName=SampleMethod2 IsPublic=True
            //MethodName=ToString IsPublic=True
            //MethodName=Equals IsPublic=True
            //MethodName=GetHashCode IsPublic=True
            //MethodName=GetType IsPublic=True

ToString, Equals, GetHashCode and GetType methods are founded in object class. So “GetMethods” method returns these methods, too. Using reflection, we can also fetch the parameters of a method.

            MethodInfo m = typeof(ReflectionExample).GetMethod("SampleMethod1");
            ParameterInfo[] parameters = m.GetParameters();
            foreach (ParameterInfo p in parameters)
            {
                Console.WriteLine("Parameter Name=" + p.Name + " " +
                                  "Type=" + p.ParameterType.Name);
            }

            //Output:
            //Parameter Name=message Type=String

Also we can create an instance of a given type and invoke its methods or properties at runtime without compiling.
This technology is named as “Late binding” or “Dynamic Invocation” in .NET. Following sample shows the sample usage.

            Type type = typeof(ReflectionExample);
            object obj = Activator.CreateInstance(type);
            MethodInfo mi = type.GetMethod("SampleMethod1");
            mi.Invoke(obj, new object[]
            {
                "Hello Method!"
            });

            //Output:
            //My name is SampleMethod1
            //Your message is Hello Method!