views:

53

answers:

3

Hello,

Let's say I've a class myClass which has few properties, such as property1, property2, perperty3, etc. Now, I'd like to populate an array with each of those properties so that, I can access each of them through its index. Is there an automatic way of doing so?

Here's an example from SportsStore (Pro ASPN.NET MVC/Steve Sanderson/Apress) on how to gather all the active controllers in the the 'Assembly'.

 var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
 where typeof(IController).IsAssignableFrom(t) 
 select t; 

 foreach(Type t in controllerTypes)
    //Do something

I wonder if there is some thing like the one above I can use to collect (only) properties of a class and store them in a array, no matter each one's type value (int, string, or custom type)

I hope I was able to express myself clearly. Otherwise I can amend the text.

Thanks for helping.

A: 

would the Type.GetProperties() method help you?

PierrOz
+4  A: 

You could use reflection:

var foo = new
{
    Prop1 = "prop1",
    Prop2 = 1,
    Prop3 = DateTime.Now
};

var properties = TypeDescriptor.GetProperties(foo.GetType());
var list = new ArrayList();
foreach (PropertyDescriptor property in properties)
{
    var value = property.GetValue(foo);
    list.Add(value);
}

and LINQ version which looks better to the eye:

var list = TypeDescriptor
    .GetProperties(foo.GetType())
    .Cast<PropertyDescriptor>()
    .Select(x => x.GetValue(foo))
    .ToArray();
Darin Dimitrov
Good answer, but requires using System.ComponentModel;
rohancragg
@Darin Dimitrov -- So, it looks like I need to instantiate the class first, right? (var Foo = new myClass()). Also, what type of object is in the array? (PropertyDescriptor?)
Richard77
No you don't need to instantiate the class at all. The `GetProperties` method expects a type, so you could call it like this: `TypeDescriptor.GetProperties(typeof(YourType))`. In my example I used an anonymous type so I instantiated it because it has no name. The array is of type `object[]` so it is not strongly typed and it cannot be as it can contain any type as the properties of your object can be of any type.
Darin Dimitrov
@Dimitrov -- I'm sorry. I'm trying to give you credit, but it's not working (I don't know why). In fact, I wanted to give credit to both of you as it's done in the ASP.NET Forums. But, I clicked first for @PierrOz. But for you it's not responding. I'll try later. Thanks a lot for answer.
Richard77
A: 

I got this from here:

foreach(Type t in controllerTypes)
{
  foreach (MemberInfo mi in t.GetMembers() )
  {
    if (mi.MemberType==MemberTypes.Property)
    {
      // If the member is a property, display information about the property's accessor methods
      foreach ( MethodInfo am in ((PropertyInfo) mi).GetAccessors() )
      {
        // do something with [am]
      }
    }
  }
}
rohancragg
`Type` has a `GetProperties()` as well.
Brian Rasmussen