Reflection in C# – The Complete Tutorial

Updated on     Kisan Patel

Reflection is defined as the process of finding out the internal elements, such as metadata, assemblies, modules and types of an application without accessing the source code.

You can use reflection to find all classes in an assembly, and all the methods, properties and events that might be supported by each of these classes.

You can inspect all the information about a class and also use reflection techniques to dynamically invoke methods of the class at runtime.

Reflection can also be used, for example, to investigate whether certain classes exist and, if so, to load and use them in your application.


Need of Reflection

Reflection is an important feature of .Net framework because it is used to extract every detail of class in .NET Framework. Reflection is of great significance while developing large applications due to its capability to collect and manipulate the data present in the assemblies and metadata of the applications.

It is also necessary because it has ability to obtain information at runtime about what is being loaded and how the members of the classes that are loaded to be called.


Using Reflection

C# reflection requires System.Reflection namespace that contains all the reflection-related classes such as Type, MemberInfo and so on. These classes are used to retrieve information from any other class under .NET Framework.

Let’s look at the simplest form of reflection – loading an assembly at runtime and investigating what information you can find out about the assembly. To do this, the following import statement is used to know about this functionality in your application:

using System.Reflection;

Now, you can use use the LoadFrom static method of the Assembly class from the Reflection library to load the individual assemblies. Now, if you have the name of the assembly you want to load in a variable named assemblyName, the following code-snippet is used:

Assembly assembly = Assembly.LoadFrom()assemblyName;

After you access the assembly object, you can investigate it. The easiest way to investigate the assembly object is to use the GetTypes method. This method returns an array of Type objects that contain information about the various kinds of types defined in this assembly. You can find out the class names, namespaces, access levels, and much more from the Type object for a given type:

Type[] types = assembly.GetTypes();

After you have the list of available types in an assembly, you can find various kinds of information from them.

Properties of the Type object

Property Purpose
IsClass Indicates that the type is a class if this property is true.
IsEnum Indicates that the type is an enumeration if this property is true.
IsInterface Indicates that the type is an interface if this property is true.
IsValueType Indicates that the type is a Value Type (a struct) if this property is true.

You can determine the type and deal with it appropriately using above four properties. Now you want to determine whether it is publicly available to use in an application.

Two properties are available for determining the access scope of a type – IsPublic and IsNotPublic properties. The IsPublic property determines a public method, while the IsNotPublic property determines a private or protected method.

For Example,

using System;
using System.Reflection;

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

            // Get assembly.
            Assembly assembly = Assembly.GetCallingAssembly();
            // Get array of types.
            Type[] types = assembly.GetTypes();

            foreach (Type t in types)
            {
                if (t.IsPublic)
                    Console.WriteLine("CLass {0} is public!", t.FullName);
                else
                    Console.WriteLine("CLass {0} is private!", t.FullName);
            }

        }
    }

    public class Animal
    {
    }

    class Veg
    {
    }
}

Here, We call Assembly.GetCallingAssembly() to get the current assembly.

the above code will produce below result…

reflection-example

Moreover, reflection enables you to explore into the implementation of a class and the parameters and methods that are used in the class.

The most common methods that are used to receive information about the types.

Property Purpose
GetTypes Retrives all types for a given assembly.
GetMethods Retrives all methods for a given current Type.
GetConstructors Retrives all constructors for a given current Type.
GetProperties Retrives all properties for a given current Type.
GetEvents Retrieves all events for a given current Type.
GetInterface Retrieves all interfaces supported by a given current Type.

So, You first retrieves the types from the assembly by using GetTypes() method to use these common methods. These method return an array of types for the assembly, which consists of classes, structures, enumerations and events. If you check for the appropriate type of the Type object and verify that it is a class or a structure, you can then apply the other methods, such as GetMethods and GetConstructors methods, to retrieve the information you are interested in.


C#

Leave a Reply