• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1702
  • Last Modified:

C# Class Name as parameter Object

This question is related to C#.
I need to create objects of the class name which i will pass as parameter. Which is very much same as RUNTIME_CLASS macro in MFC. My requirement is i want to implement the same thing in C# without using the pointers. I am including a sample code which i am using in my project

switch (classname)
    case "Class1"
                     Class1 obj1 = new Class1()
    case "Class2"
                     Class2 obj2 = new Class2()

I want to remove the switch statement and I want to use some thing like RUNTIME_CLASS. But I want to stick with managed code.

sandy ware
sandy ware
  • 2
1 Solution
Mayank SAssociate Director - Product EngineeringCommented:
If you are on C# .NET, you can use this for making objects of any class:

using System.Reflection ;


Assembly a = Assembly.Load ( assemblyName ) ;
// catch FileNotFoundException - if it is thrown, then the assembly could not be loaded

// You can add: Type t = a.getType ( className, false, true ) ; if ( t == null ) -> Class cannot be instantiated

object instance = a.CreateInstance ( className ) ;

// Now you can cast it to any appropriate instance if you want.

Class1 obj = ( Class1 ) instance ;

It'd be better to check:

if ( instance is Class1 )
  Class1 obj = ( Class1 ) instance ;
sandy wareSoftware EngineerAuthor Commented:
I have tried this code and the Createinstance is always returns null.

object instance = a.CreateInstance ( className ) ; // instance is always null

 I tried with other assembly functions like, GetAssembly and GetExecutableAssembly and all those stuff. But same result.  MyApplication is a simple Exe and it not refers to any other DLL. Only thing it is having different name spaces. I tried by giving a class name which have name space which is equal to application exe name. That's also not working. The Assembly.Load function getting the assembly properly which i can view through watch window.

Please help me
Mayank SAssociate Director - Product EngineeringCommented:
The className should contain the complete name, something like: "namespace.sub1.sub2.ClassName". Did you give it that way?

If you have:

namespace X.Y.Z
  public class A

The className should be: "X.Y.Z.A"
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now