0

when I receive a parameter which has a class name, how can I declare a proper variable with the class name? For example, if I have a method as follows:

public void foo(string class_name)
{
    object var1 = Activator.CreateInstance(Type.GetType(class_name));
}

CreateInstance() returns object. But I'd like to cast the object type to the class_name_type as follows.

class_name_type var1 = (class_name_type)Activator.CreateInstance(Type.GetType(class_name));

How can I declare var1 as a class_name_type correctly?

Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • 1
    Casting just changes the compile-time reference you have. It doesn't convert the type (it's already the type you created). So unless you have *compile-time* information about the type, there's no meaning in casting it. That's saying nothing about Generics. – madreflection Apr 23 '20 at 20:55
  • 2
    You can't declare that variable correctly, that has to be done at compile time. Since you only know the type at runtime, you can't do it compile time. **Why** do you want to declare it with the right type at compile time? – Lasse V. Karlsen Apr 23 '20 at 20:59
  • If you have `class_name_Type` available at compile time (which is necessary to get your last code snippet to compile), why use this at all? Can't you just actually construct `var1` from the class' constructor(s)? – Sean Skelly Apr 23 '20 at 21:00
  • Use common interface if you have access to implementation. Othewise use dynamic but it is not safe. – Radik Apr 23 '20 at 21:05
  • There are hundreds of code tables and correspondingly declared model classes. In order to maintain these, I displayed the table names in the DataGridView, and when the user selects one code table, I want to display the contents in another DataGridView and then add or update records. By the way, I wanted to find a way to handle it dynamically because it requires hundreds of case statements to be processed at compile time. – 이교준 Apr 23 '20 at 21:09
  • That comment should be [edit]ed into the question. That's the real problem you're trying to solve. Anyway, you need to use reflection to examine the properties of the type that's selected. – madreflection Apr 23 '20 at 21:18
  • As @madreflection said you need to [edit] question into "How to do {what you want to achive}, I tried {that impossible approach of using type unknown at compile time}" to be answerable... At this point question is duplicate of one of many similar questions which all essentially have the same answer "not possible, for each particular case there is alternative you can use". – Alexei Levenkov Apr 23 '20 at 21:51

0 Answers0