Reputation: 14565
How can i loop over an object's properties and get the value of a property.
i have an object that has several properties filled with data. the user specifies what property he wants to view by providing the name of the property, and i need to search for the property in the object and return its value to the user.
How can i achieve this?
i wrote the following code to get the property but couldn't get the value of that prop:
public object FindObject(object OBJ, string PropName)
{
PropertyInfo[] pi = OBJ.GetType().GetProperties();
for (int i = 0; i < pi.Length; i++)
{
if (pi[i].PropertyType.Name.Contains(PropName))
return pi[i];//pi[i] is the property the user is searching for,
// how can i get its value?
}
return new object();
}
Upvotes: 3
Views: 3796
Reputation: 4228
Try this (code inserted inline):
public object FindObject(object OBJ, string PropName)
{
PropertyInfo[] pi = OBJ.GetType().GetProperties();
for (int i = 0; i < pi.Length; i++)
{
if (pi[i].PropertyType.Name.Contains(PropName))
{
if (pi[i].CanRead) //Check that you can read it first
return pi[i].GetValue(OBJ, null); //Get the value of the property
}
}
return new object();
}
Upvotes: 8
Reputation: 7376
You call the PropertyInfo.GetValue method passing in the object to get the value for.
public object FindObject(object OBJ, string PropName)
{
PropertyInfo[] pi = OBJ.GetType().GetProperties();
for (int i = 0; i < pi.Length; i++)
{
if (pi[i].Name == PropName)
{
return pi[i].GetValue(OBJ, null);
}
}
return new object();
}
All reflection types, including PropertyInfo are bound to the class. You have to pass in the instance of the class in order to get any instance-related data.
Upvotes: 0
Reputation: 1324
public static object FindObject(object obj, string propName)
{
return obj.GetType().GetProperties()
.Where(pi => pi.Name == propName && pi.CanRead)
.Select(pi => pi.GetValue(obj, null))
.FirstOrDefault();
}
Upvotes: 1
Reputation: 1503944
To get the value from a PropertyInfo
, you call GetValue
:) I doubt that you really want to be getting the name of the property type mind you. I suspect you want:
if (pi[i].Name == PropName)
{
return pi[i].GetValue(OBJ, null);
}
Note that you should probably make sure that the property isn't an indexer, and is readable and accessible etc. LINQ is a good way of filtering things, or you could just use Type.GetProperty
to get straight to the property with the required name, instead of looping - and then perform all the validation that you need.
You should also consider following naming conventions and using a foreach
loop. Oh, and I'd probably either return null or throw an exception if the property can't be found. I can't see how returning a new empty object would be a good idea.
Upvotes: 6