Tuesday 21 August 2018

C#: Introduction to Reflections

Reflections provides the facility to examine or modify the runtime behavior of running applications. By using reflections, you can inspect interfaces, classes, fields and methods at run time.

Getting the reference to Type class is the starting point of Reflections.

How to get Type instance?
Following ways are used to get the type instance.

Way 1: By calling the getType method of Type class, you can get the Type instance. You need to pass the fully qualified name of the class, as an argument to getType method.

Example
Type type = Type.GetType("Student");

Way 2: By using the ‘typeof’ method, you can get Type instance.

Example
Type type = typeof(Student);

Way 3: By using the instance of given class, you can get the type object.

Student s1 = new Student("Hari Krisha", 1);
Type type = s1.GetType();

Once you got the type object, you can use type reference, to query the metadata of given class, struct etc.,

Following is the complete working application.

Program.cs
using System;
using System.Reflection;

class Student
{
    public String name;
    public int id;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public Student(String name, int id)
    {
        this.name = name;
        this.id = id;
    }

}

class Program
{
    public static void printTypeInformation(Type type)
    {
        String name = type.Name;
        MemberInfo[] memberInfo = type.GetMembers();
        MethodInfo[] methodInfo = type.GetMethods();
        ConstructorInfo[] constructorInfo = type.GetConstructors();

        Console.WriteLine("Name : {0}", name);

        Console.WriteLine("\nMembers are\n");
        foreach(MemberInfo info in memberInfo)
        {
            String memberName = info.Name;
            Console.WriteLine(memberName);
        }

        Console.WriteLine("\nMethods are\n");
        foreach (MethodInfo info in methodInfo)
        {
            String memberName = info.Name;
            Console.WriteLine(memberName);
        }

        Console.WriteLine("\nConstructors are\n");
        foreach (ConstructorInfo info in constructorInfo)
        {
            Console.WriteLine(info);
        }


    }

    static void Main(string[] args)
    {
        Student s1 = new Student("Hari Krisha", 1);
        Type type = s1.GetType();

        printTypeInformation(type);
    }
}

Output
Name : Student

Members are

getName
setName
getId
setId
ToString
Equals
GetHashCode
GetType
.ctor
name
id

Methods are

getName
setName
getId
setId
ToString
Equals
GetHashCode
GetType

Constructors are

Void .ctor(System.String, Int32)





Previous                                                 Next                                                 Home

No comments:

Post a Comment