0

I searched on the site for an answer that I needed, but I could not find it...

I have this:

string sNameOfClass="BusNode";

And the class already exists, and has its own properties.

Now I need to do something like this, but I dont know how...

sNameOfClass variable1 = new sNameOfClass()

and use varible1 forward in program as a normal variable...

so like

coorinateClass cs = new ks();
cs.a=11;
cs.b=33;
cs.c=55;

Any clues?

Thank you in advance

Alex
  • 937
  • 3
  • 20
  • 44
Stefan
  • 13
  • 2

3 Answers3

1

If you need to manage a class with its name you can use this:

//your class name
string sNameOfClass = "YourNameSpace.BusNode";
//create type class from your class name
Type T = Type.GetType(sNameOfClass);
//create new instance of class
var NewInstanse = Activator.CreateInstance(T);
//set property 
T.GetProperty("a").SetValue(NewInstanse, 11);
//get value of property
var a = T.GetProperty("a").GetValue(NewInstanse);
aDDin
  • 53
  • 3
  • An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll Additional information: Value cannot be null. ---- error at line var NewInstanse = Activator.CreateInstance(T); – Stefan Jul 08 '16 at 08:55
  • i see Type T = Type.GetType(sNameOfClass); is null, – Stefan Jul 08 '16 at 08:58
  • i see the problem, it does not recognises the namespace for that class... but that is my problem...thx bro u helped me a lot.... – Stefan Jul 08 '16 at 09:07
1

You can use Activator.CreateInstance Method

Check out this link : Activator.CreateInstance Method (String, String)

Kahbazi
  • 14,331
  • 3
  • 45
  • 76
0
string sNameOfClass="BusNode";

switch (sNameOfClass)
{
 case "BusNode":
       BusNode variable1 = new BusNode()
       break;
 case "...."
       break;
}
andy
  • 5,979
  • 2
  • 27
  • 49
  • Above code is useful for small number of classes....Please check once "CreateInstance vs new" http://stackoverflow.com/questions/1649066/activator-createinstancet-vs-new – andy Jul 08 '16 at 08:56