Reflection In C#


Reflection
                This language feature allows you to inspect the assemblies’ metadata (information of types).
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 { get; set; }
        public int Age { get; set; }

        [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;
        }
    }



Comments

Popular posts from this blog

SSIS Merge Join - Both inputs of the transformation must contain at least one sorted column, and those columns must have matching metadata SSIS

jsGrid

Add Item to SharePoint List with attachment using client object model