Question

I have been reading over old questions asked ans searching MSDN help but I cant really understand what a PropertyInfo is, specifically relating to the question of looping through an array list

c# foreach (property in object)... Is there a simple way of doing this?)

I made a simple class

public MyClass
{
public double myProperty; // etc
}

and then I add class objects to a list. I want to loop through the list, to change just a property of each object

foreach ( MyClass i in MyClassList)
{
foreach ( double myProperty in i.GetType().GetProperties() )
{
// do something
}


}

but I get an error. In the linked question (above) it says to use PropertyInfo instead of 'double. what is the PropertyInfo that should replace the 'double' of myProperry and what does it represent?

Was it helpful?

Solution

PropertyInfo simply represents the fact that a property is defined for that type; it isn't per-object - it is for the type. You don't need any instances to get a PropertyInfo.

First, however, note that myProperty is not currently a property: let's fix that first:

public MyClass
{
    public double MyProperty {get;set;}
}

now we can find out about that property, either by asking about "all the properties it has", i.e.

PropertyInfo[] props = typeof(MyClass).GetProperties();

or an individual property, perhaps getting the name from configuration at runtime:

PropertyInfo prop = typeof(MyClass).GetProperty("MyProperty");

You can inspect a PropertyInfo for the name, type, attributes, etc - very useful for library code. However, in regular code the simplest option is just to use static C#:

foreach(MyClass obj in MyClassList) {
    obj.MyProperty = 123.45;
}

if you need to do this via reflection, then you can use SetValue:

foreach(MyClass obj in MyClassList) {
    prop.SetValue(obj, 123.45, null);
}    

however, reflection is relatively slow unless you go to greater lengths. For example, another alternative for targeting the "I'll know the names at runtime" scenario would be FastMember; then you can do:

var accessor = TypeAccessor.Create(typeof(MyClass));
string propName = "MyProperty";
object value = 123.45;
foreach(MyClass obj in MyClassList) {
    accessor[obj, propName] = value;
}

which will be much faster than raw reflection, while having more flexibility in terms of finding property-names at runtime.

OTHER TIPS

You probably want this:

foreach (MyClass i in MyClassList)
{
    foreach (var myProperty in i.GetType().GetProperty("myProperty") )
    {
        myProperty.SetValue(i, 1.23);
    }
}

This is equivalent to:

foreach (MyClass i in MyClassList)
{
    i.myProperty = 1.23;
}

GetProperties returns a collection of PropertyInfo Objects.

You then need to iterate (or search) that collection for the property you want.

See here for an example of using GetProperties()

http://rhondatipton.net/2010/02/28/using-getproperties-in-c/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top