1.

Why Reflection introduced in C#?

Answer»

Reflection provides METADATA information on types, modules, assemblies etc. at runtime. It is also useful in MULTIPLE situations and this is the reason it was introduced in C#.

Some of the situations when reflections are useful in C# are given as follows:

  1. For late binding to methods and properties, reflections are quite useful.
  2. Types can be examined and instantiated in an assembly using Reflection.
  3. New types can be created at runtime using Reflections.
  4. Reflection can be used with the program metadata attributes.

A program that demonstrates the usage of System.Reflection using the GetType() METHOD in C# is given as follows:

using System;   using System.Reflection;   public class Demo   {      public static void Main()      {        TYPE type1 = typeof(object[]);        Type type2 = "this is a string".GetType();        Type type3 = 50.GetType();          Console.WriteLine(type1);        Console.WriteLine(type1.Name);        Console.WriteLine(type2);        Console.WriteLine(type2.Name);        Console.WriteLine(type3);          Console.WriteLine(type3.Name);    } }

The output of the above program is as follows:

System.Object[] Object[] System.String String System.Int32 Int32


Discussion

No Comment Found