bnfdvn
bnfdvn

Reputation: 1

string as a class name

I have a class called cNormType. I want to create another instance of this class with the name contained in the string sNT. The namespace is QM. I want to pass five parameters to the constructor for this class (sNN,sTN,sDN,sHI,sLO).

I tried:

Type t1 = Type.GetType("QM.cNormType", sNT); 
Activator.CreateInstance(t1, [sNN,sTN,sDN,sHI,sLO]);

I get 18 errors so obviously I have this wrong. Would someone be so kind as to show me what I need to do?

Upvotes: 0

Views: 125

Answers (3)

ClickRick
ClickRick

Reputation: 1568

I'm making some really wild assumptions here about what you're trying to do, but does this achieve what you actually wanted?

Dictionary<string, cNormType> norms = new Dictionary<string, cNormType>();
   ...
norms[sNT] = new cNormType(t1, sNN, sTN, sDN, sHI, sLO);

norms[sNT] is then how you would refer to each of the instances (Bob, Sally, etc).

Upvotes: 0

jmcilhinney
jmcilhinney

Reputation: 54487

What exactly are those brackets in the second statement supposed to be doing? Is that an attempt to create an array? That's not how you create an array and you don't need to create one anyway. That second parameter is declared params, which means that you can just pass discrete arguments and the system will package them as an array.

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66501

I can't test the whole thing since I don't have all your code, but remove the square brackets:

Type t1 = Type.GetType("QM.cNormType");

cNormType newNorm =
    (cNormType)Activator.CreateInstance(t1, sNT, sTN, sDN, sHI, sLO);

I'm not sure what you mean by creating an instance of the class using the name in sNT.

Upvotes: 0

Related Questions