Fairly simple I think

  • Thread starter Thread starter Robert Towne
  • Start date Start date
R

Robert Towne

If I have a string representation of a property such as
"MyObject.SomeProperty", how would I then create a "MyObject" object and
invoke "SomeProperty". Any assistance would be appreciated. Thanks.
 
Robert,

Look in the System.Reflection namespace.

Specifically, you have to load the Type instance for MyObject, and then
pass that to the static CreateInstance method on the Activator class to
create an instance. Then, from the type, you have to get the PropertyInfo
(through the GetProperty method on the Type) for the SomeProperty property.

Once you have that, you can get the value through the GetValue method on
the PropertyInfo that is returned from GetProperty.

Hope this helps.
 
Look in the System.Reflection namespace.
Specifically, you have to load the Type instance for MyObject, and then
pass that to the static CreateInstance method on the Activator class to
create an instance. Then, from the type, you have to get the PropertyInfo
(through the GetProperty method on the Type) for the SomeProperty
property.

Once you have that, you can get the value through the GetValue method
on the PropertyInfo that is returned from GetProperty.

Hope this helps.

Ok. I took a quick look and I think I'm on track now. Thanks very much
(appreciated).
 
Robert Towne said:
If I have a string representation of a property such as
"MyObject.SomeProperty", how would I then create a "MyObject" object and
invoke "SomeProperty". Any assistance would be appreciated. Thanks.

Something like:

string initializer = "It's Chinatown, Jake";
Type type = typeof(string);
object o = Activator.CreateInstance(type, new object[] {
initializer.ToCharArray() });
PropertyInfo info = type.GetProperty("Length");
Debug.WriteLine(info.GetValue(o, null));

///ark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top