0

Is it possible to create a class which does not exist with specific name from a dynamic string. I'm asking this because I want to create a class based on some string result.

If it is possible please share some example or some reference link.

I see that my question is confusing, so here is more clarification:

Assume that I have a method/function/procedure which returns a string - MyNewClassName(). I want to create a class with name equal to the result of MyNewClassName(), which is dynamic and also it is a custom name.

EDIT from comment
I'll use it as some kind of debugging, because I'm trying to fix some exception remotely, the problem is that the system does not provide the exception message only the type of the exception. So my idea is to create custom exception named with the result of the actual exception.

12
  • 1
    Why do you need a dynamicly named class? - and how would you reference it in your code? Commented Nov 25, 2013 at 12:20
  • 1
    you mean class or instance of a class ? Commented Nov 25, 2013 at 12:21
  • Take a look at System.Reflection, System.CodeDom.Compiler and Microsoft.CSharp. Commented Nov 25, 2013 at 12:22
  • @Sriram Sakthivel: I want to create a class dynamically not an instance of a class. I think that all answers below are related to creating of an instance of a class. Commented Nov 25, 2013 at 12:57
  • 2
    See for instance stackoverflow.com/q/3862226/121309 Commented Nov 25, 2013 at 13:15

2 Answers 2

2

If you have the classes assembly qualified full name in a string (obtained from whereever, the user can type it in or something), you can do the following:

var name = "MyNameSpace.MyType, MyAssembly";
var type = Type.GetType(name);
var instance = Activator.CreateInstance(type);

This assumes the assembly you specify is already loaded.

Sign up to request clarification or add additional context in comments.

5 Comments

Dear anonymous downvoter, please leave a comment, if you don't, I cannot improve my post.
Sure.. This won't work unless and until you have assembly qualified name, or (type exist in mscorlib/current assembly). And question is not clear though.
FYI I've answered it here
@SriramSakthivel You are right, I edited my answer.
I removed my downvote.. +1..
1

You can get an instance of a type by using Activator.CreateInstance(type) . for getting type by type name see here: Get Type by Name

1 Comment

Oh man.. +1 for referring my answer.. But if you feel question is duplicate, vote to close.. or flag it.. That's what am going to do..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.