call object from string variable

  • Thread starter Thread starter XenofeX
  • Start date Start date
X

XenofeX

How can i call to object from string variable ?

For instance
string x = "textBox1";

i want to call the object which name is stored in the x string
variable. The most important thing is the object type is unknown. x
may be stored "comboBox1".

I think Activator.CreateInstance makes it but how ?
 
XenofeX said:
How can i call to object from string variable ?

For instance
string x = "textBox1";

i want to call the object which name is stored in the x string
variable.

Point of terminology - you don't call objects, you create instances of
types - or you call methods. Similarly, I *think* you mean you want to
create an instance of the type that the *variable* whose name is stored
in the string.
The most important thing is the object type is unknown. x
may be stored "comboBox1".

I think Activator.CreateInstance makes it but how ?

Use someType.GetField(x), possibly with some binding flags depending on
exactly what you want, to get the FieldInfo for the relevant field.
That includes the type it's declared as using the FieldType. (someType
here is the type you want to "look up" the variable name in.)

Do you then need to set the value of the variable to the newly created
instance? If so, use FieldInfo.SetValue.

Here's an example:

using System;
using System.Reflection;

class Foo
{
public void SayHi()
{
Console.WriteLine ("Hi!");
}
}

class Test
{
Foo bar;

static void Main()
{
Test t = new Test();
t.Populate("bar");
t.bar.SayHi();
}

void Populate(string variable)
{
// Get the field
FieldInfo fi = typeof(Test).GetField(variable,
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic);
// Create the instance
object obj = Activator.CreateInstance(fi.FieldType);
// Populate the variable
fi.SetValue(this, obj);
}
}

Compiling this gives a warning about "Test.bar never being assigned
to" - little does it know!
 
First of all thanks for your reply. Although you wrote the code that
describes the seting property. I don't want to set the property, i want
to get property's value.

How can get the value of property ?

Regards,
 
murat guzel said:
First of all thanks for your reply. Although you wrote the code that
describes the seting property. I don't want to set the property, i want
to get property's value.

Firstly, I didn't do anything with a property - I did it with a field.
There's a definite difference.
How can get the value of property ?

Assuming you still mean field, use FieldInfo.GetValue.
 
Back
Top