Reflections in C#

One of the most useful properties of C# language is its ability to get information about the assembly, classes and members variables at run time. This functionality is achieved via reflection objects.

Reflection classes belong to system.Reflection namespace and provide several functionalities to get useful information from the .NET managed code at run time. Reflection classes also let developers modify the characteristics of types and assemblies on the go.

Reflections are also used for defining new types and members at run time. In the following example, the method name is accessed by the code within the method. Also, the name of the currently executing assembly is being accessed within that method. Finally the type of object is being accessed within the main method. Have a look at this example.

´╗┐using System;
using System.Reflection;
namespace CSharpTutorials {

    public class Vehicle {

        public void VehicleMessage() {
            // Code to get name of the method in which code is
            string methodname = MethodBase.GetCurrentMethod().Name;
            Console.WriteLine("This code is within "+methodname+" method");


            // code to get object of current assembly name
            string assemblyname = Assembly.GetExecutingAssembly().GetName().Name;
            Console.WriteLine("This code is within " + assemblyname + " assembly");
        }
    }

    class Tutorial {
        static void Main(string[] args)  {
            Vehicle veh = new Vehicle();
            veh.VehicleMessage();
            Type typeofobject = veh.GetType();
            Console.WriteLine(typeofobject.Name);
            Console.ReadKey();
        }
    }
}

Download the code

The first thing to notice in the above code is the use of System.Reflection namespace via using. This statement prevents developers from writing fully qualified type names. Next, a class named Vehicle has been defined and in this class, a method named VehicleMessage has been created. Inside this method, Reflection type MethodBase is being used to get the name of the current method. Next, Assembly class is being used to get the name of the currently executing assembly via the GetExecutingAssembly method.

Finally, To get the name of the class of the object the GetType method is called on the object inside the Main method.

<<< Properties in C#Hashtable and SortedList in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .