Reflection in C#


In this article, I would like to explain how to load an assembly dynamically and display its forms with the help of Reflection. Consider a situation where you want to display all forms of an unknown assembly at runtime. 

Reflection_Assembly is a simple c# library which is having 3 windows forms.

Step 1: Loading an assembly form the specified path.

string path = Directory.GetCurrentDirectory() + @"\Reflection_Assembly.dll";
try
{
    asm = Assembly.LoadFrom(path);
}
catch (Exception)
{
}

Step 2: Getting all forms of an assembly dynamically & adding them to the list type.

List<Type> FormsToCall = new List<Type>();
Type[] types = asm.GetExportedTypes();
foreach (Type t in types)
{
    if (t.BaseType.Name == "Form")
        FormsToCall.Add(t);
}

Step 3:

int FormCnt = 0;
Type ToCall;
while (FormCnt < FormsToCall.Count)
{
     ToCall = FormsToCall[FormCnt];
     //Creates an instance of the specified type using the constructor that best matches the specified parameters.
     object ibaseObject = Activator.CreateInstance(ToCall);
     Form ToRun = ibaseObject as Form;
     try
     {
          dr = ToRun.ShowDialog();
          if (dr == DialogResult.Cancel)
          {
             cancelPressed = true;
             break;
          }
          else if (dr == DialogResult.Retry)
          {
             FormCnt--;
             continue;
          }
     }
     catch (Exception)
     {
     }
     FormCnt++;
}