[Mono-list] Retrieving the Properties of a class at runtime

Dmitry Kostenko bis0n@mail.ru
Thu, 30 Dec 2004 17:05:44 +0200


Hi, Shawn.
Here's the sample:

--CUT--
using System.Reflection;

public class  A{
    public int a { get { return 1 ; } }
    public int b { get { return 2 ; } }
}

public class Program {
    public static void Main() {
       object a = new A();
       foreach (PropertyInfo prop in a.GetType().GetProperties()) {
          System.Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(a, new 
object[0]));
       }
    }
}
--END CUT--

object.GetType() returns System.Type() which has GetProperties() method that 
returns all public properties. There's an overload for this method to get 
all/private/public/protected/internal etc. properties.

Each property is represented by a PropertyInfo object which has Name and a 
GetValue/SetValue pair.

The documentation is at http://msdn.microsoft.com/, the API is quite simple 
and straightforward. There should also be API index/reference in monodoc.

Regards,
Dmitry Kostenko
.NET Developer

Shawn Vose wrote:
> Can someone direct me to documentation on how to iterate over only the 
> properties in a class at runtime. I have a class that is nothing but 
> properties and instead of typing out 
> Console.WriteLine(someObject.someProperty) it would rather iterate over 
> the available properties.
> 
> Ist this where System.Refelection comes into play?
> 
> _______________________________________________
> Mono-list maillist  -  Mono-list@lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list
> 
>