C# Lessons

The simplest explanation of the reflection #L2

At first, it took me some time to understand what is the reflection and how it works. Here, I will try to give you very short and simple definition:

Reflection is a mechanism that allows us to access the structure (classes, methods, resources) of a given assembly during the program’s operation.

Thanks to it, we can get information about the metadata of classes or objects. To make this possible, we need to add the System.Reflection namespace to our code.

To understand this definition better, check out this code:

using System;
using System.Reflection;

namespace MainProgram
{
  class Program
  {
    public virtual void WriteInfo (string information)
    {
      Console.WriteLine(information);
    }
    static void Main(string[] args)
    {
      Program program = new Program();
      //Type information
      Type programInfo = program.GetType();
      //Method information
      MethodInfo programMethodInfo = programInfo.GetMethod("WriteInfo");

      Console.WriteLine("Type information");
      Console.WriteLine("Full name: \t" + programInfo.FullName);
      Console.WriteLine("Base type: \t" + programInfo.BaseType.ToString());
      Console.WriteLine("Namespace: \t" + programInfo.Namespace);

      Console.WriteLine("\nMethod information:");
      Console.WriteLine("Method name: \t" + programMethodInfo.Name);
      Console.WriteLine("Return type: \t" + programMethodInfo.ReturnType);
      Console.WriteLine("Is this method virtual?: \t" + programMethodInfo.IsVirtual);
      Console.Read();
    }
  }   
}

Leave a Reply