How can you get a reference to a property by name?

G

Guest

I need to get a reference to an objects property by name. I know how to use
the PropertyDescriptor's GetValue and SetValue methods to get and set the
value of an objects property. But my issue is I need to get a reference to
the property itself.

For example I need to do this:

public Person PopulatePerson(Person p)
{
GetReference(p, "FirstName") = "Chris";
return p;
}

The above example is over simplified compared to what I need to do, but the
end result is the same. I wont know what the property is I need to set until
runtime.

Please keep sample to either C# or VB.NET. Thanks
 
J

Jon Skeet [C# MVP]

crpietschmann said:
I need to get a reference to an objects property by name. I know how to use
the PropertyDescriptor's GetValue and SetValue methods to get and set the
value of an objects property. But my issue is I need to get a reference to
the property itself.

For example I need to do this:

public Person PopulatePerson(Person p)
{
GetReference(p, "FirstName") = "Chris";
return p;
}

The above example is over simplified compared to what I need to do, but the
end result is the same. I wont know what the property is I need to set until
runtime.

Please keep sample to either C# or VB.NET. Thanks

Use typeof(Person).GetProperty("FirstName").
 
G

Guest

I already know how to do that. I need to get a Reference to the actual
property of the object.

I need to do this:
GetReference(p, "FirstName") = "Chris";
And this:
string strName = GetReference(p, "FirstName");

Any ideas?
 
J

Jon Skeet [C# MVP]

crpietschmann said:
I already know how to do that. I need to get a Reference to the actual
property of the object.

The PropertyInfo returned by GetProperty *is* the property.
I need to do this:
GetReference(p, "FirstName") = "Chris";
And this:
string strName = GetReference(p, "FirstName");

Any ideas?

Once you've got a PropertyInfo, you can fetch and set the value of the
property for a specific instance using the GetValue and SetValue
methods.
 

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

Top