user3475971
user3475971

Reputation: 11

How to convert a String into a Class reference

I have the string class name and I want to convert it to a class reference

if (System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()] != null)                                     
{
    (System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()] as PC_01).accept();
}

I want use string "PC_01" instead of class PC_01.

Upvotes: 0

Views: 96

Answers (2)

Yucel
Yucel

Reputation: 2673

If you are want to express the type of an object as string, you can do it with help of Type class, and use dynamic to invoke a method of this instance.

object obj = System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()];
Type t = Type.GetType("myNamespace.PC_01, myAssembly");

if (obj.GetType() == t)
{
   ((dynamic)obj).accept();
}

Upvotes: 0

Related Questions