Wednesday 3 February 2016

What is reflection in C#? Give example


Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values and objects to the application.

Reflection provides objects (of type Type) that encapsulate 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

Example 1:-

using System;
using System.Reflection;

namespace ConsoleDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Reflection.Assembly info = typeof(System.Int32).Assembly;

            System.Console.WriteLine(info);

            Console.ReadLine();
        }
    }

}


Output:-








Example -2

using System;
using System.Reflection;

namespace ConsoleDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {

            var t = typeof(MyClass);

            foreach (var m in t.GetMethods())
            {
                Console.WriteLine(m.Name);
            }
          

       // Or you can use MemberInfo  object to hold the object of typeof


       //System.Reflection.MemberInfo info = typeof(MyClass);
        // object[] attributes = info.GetCustomAttributes(true);
        // for (int i = 0; i < attributes.Length; i++)
        // {
        //    System.Console.WriteLine(attributes[i]);
        // }


            System.Reflection.Assembly info = typeof(System.Int32).Assembly;

            System.Console.WriteLine(info);

            Console.ReadLine();
        }
    }


    public class MyClass
    {
        public int Add(int x, int y)
        {
            return x + y;
        }

        public int Subtract(int x, int y)
        {
            return x - y;
        }
    }
}



Output:-















No comments:

Post a Comment