Friday, January 11, 2019

Reflection In C#

Reflection
                This language feature allows you to inspect the assemblies’ metadata (information of types) like properties and methods.

Use of Reflection
1.       Late binding
2.       Allow to inspect the content of assembly

How to use Reflection

public class Program
    {
        static void Main(string[] args)
        {
            Type tp = Type.GetType("ConsoleApplication1.Calculator");
            PropertyInfo[] pInfo = tp.GetProperties();
            MethodInfo[] minfo = tp.GetMethods();

            //Create Instance
            object objCal = Activator.CreateInstance(tp);

            //Invoke Methods
            List<int> lst = new List<int> { 1, 2, 3 };
            object[] param = new object[] { lst };
            int result =(int)tp.InvokeMember("AddNumbers"BindingFlags.InvokeMethod, null, objCal, param);
        }
    }

    public class Calculator
    {
        public string Name { getset; }
        public int Age { getset; }

        [Obsolete("This method is obsolete, Use new method AddNumbers(List)",true)]
        public int AddTwoNumbers(int num1, int num2)
        {
            return num1+num2;
        }

        //Add a method to add N numbers and it will obsolute the AddNumbers(int,int)
        public int AddNumbers(List<int> numbers)
        {
            int total = 0;
            foreach(var num in numbers)
            {
                total += num;
            }
            return total;
        }
    }



No comments: