This question already has an answer here:
- Using PropertyInfo.GetValue() 1 answer
I have the following class:
public class MagicMetadata
{
public string DataLookupField { get; set; }
public string DataLookupTable { get; set; }
public List<string> Tags { get; set; }
}
And an instance of it, let's say:
MagicMetadata md = new MagicMetadata
{
DataLookupField = "Engine_Displacement",
DataLookupTable = "Vehicle_Options",
Tags = new List<String>{"a","b","c"}
}
Given the MagicMetadata
instance, I need to create a new object for each property, e.g.:
public class FormMetadataItem
{
public string FormFieldName { get; set; }
public string MetadataLabel { get; set; }
}
So I am trying something like this as per c# foreach (property in object)... Is there a simple way of doing this?
foreach (PropertyInfo propertyInfo in md.GetType().GetProperties())
{
new FormMetaData
{
FormFieldName = propertyInfo.Name,
MetadataLabel = propertyInfo.GetValue(metadata.Name) //This doesn't work
}
}
What I don't understand is how I get the value for the property that I am looping through. I don't understand the documentation at all. Why do I need to pass it the object? What object?
P.S. I looked through the existing answers here, and I don't see a clear answer.
Update to:
PropertyInfo.GetValue()
expects an instance of the object that contains the property whose value you're trying to get. In yourforeach
loop, that instance seems to bemd
.Also note the distinction between
property
andfield
in C#. Properties are the members that haveget
and/orset
:And while reflecting, you need to access these members separately via the
myObj.GetType().GetProperties()
andmyObj.GetType().GetFields()
methods.