Home   Cover Cover Cover Cover
 

Properties of a class

/csbook/solutions/18/A14.cs
using System;
using System.Reflection;

// Outputs all public properties of a type to the screen
public class ListProperties {
  
  static void Main(string[] arg) {
    if (arg.Length > 0) {
      Type t = Type.GetType(arg[0]);
      if (t != null) {
        foreach (PropertyInfo prop in t.GetProperties()) {
          MethodInfo get_ = prop.GetGetMethod();
          MethodInfo set_ = prop.GetSetMethod();
          Console.Write("public {0} {1} ", prop.PropertyType, prop.Name);
          Console.Write("{ ");
          if (get_ != null) Console.Write("get; ");
          if (set_ != null) Console.Write("set; ");
          Console.WriteLine("}");
        }
      } else Console.WriteLine("-- {0} is not a type name", arg[0]);
    } else Console.WriteLine("-- class name expected");
  }
}