How can you get a reference to a property by name?  
Author Message
crpietschmann





PostPosted: Visual C# General, How can you get a reference to a property by name? Top

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




Visual C#18  
 
 
boban.s





PostPosted: Visual C# General, How can you get a reference to a property by name? Top

You need to create indexer property that will be used to access some property with property name:
[IndexerName("Item")]
public new string this [string name]
{
get
{
switch (name)
{
case "FirstName":
return this.FirstName;
......
}
}
set
{
switch (name)
{
case "FirstName":
this.FirstName = value;
......
}
}
}



 
 
PhilipRieck





PostPosted: Visual C# General, How can you get a reference to a property by name? Top

 

Instead of using a PropertyDescriptor, you can use  a PropertyInfo (which also has GetValue and SetValue) returned from a type's GetProperty() method:

 

public Person PopulatePerson(Person p)
{
   Type personType = typeof(Person); // or,  = p.GetType() to be more "dynamic"

    personType.GetProperty("FirstName").SetValue(p, "Chris", null);

    return p;
}