views:

269

answers:

4

Say I have a class:

public class TestClass
{
  public String Str1;
  public String Str2;
  private String Str3;

  public String Str4 { get { return Str3; } }

  public TestClass()
  {
    Str1 = Str2 = Str 3 = "Test String";
  }
}

Is there a way (C# .NET 2) to iterate through the Class 'TestClass' and print out public variables and attributes?

Remeber .Net2

Thank you

A: 

You can to use reflection

TestClass sample = new TestClass();
BindingFlags flags = BindingFlags.Instance | 
    BindingFlags.Public | BindingFlags.NonPublic;

foreach (FieldInfo f in sample.GetType().GetFields(flags))
    Console.WriteLine("{0} = {1}", f.Name, f.GetValue(sample));

foreach (PropertyInfo p in sample.GetType().GetProperties(flags))
    Console.WriteLine("{0} = {1}", p.Name, p.GetValue(sample, null));
Rubens Farias
A: 

You can do this using reflection.

Here is an article that uses reflection for extensibility.

Oded
+8  A: 

To iterate through public instance properties:

Type classType = typeof(TestClass);
foreach(PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
  Console.WriteLine(property.Name);
}

To iterate through public instance fields:

Type classType = typeof(TestClass);
foreach(FieldInfo field in classType.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
  Console.WriteLine(field.Name);
}

If you also want to include non-public properties, add BindingFlags.NonPublic to the arguments of GetProperties and GetFields.

Håvard S
+1 for being the only person to actually answer the question directly. :P
Sapph
This is exactly what i needed! Thank you
Theofanis Pantelides
A: 

To get Properties of a Type we will use:

Type classType = typeof(TestClass);
    PropertyInfo[] properties = classType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

To get Attributes defined of a Class we will use:

Type classType = typeof(TestClass);
object[] attributes = classType.GetCustomAttributes(false); 

Boolean flag passed is the Inheritance flag, whether to search in inheritance chain or not.

To get attributes of a property we will use:

propertyInfo.GetCustomAttributes(false); 

Using Harvard Code given above:

Type classType = typeof(TestClass);
object[] classAttributes = classType.GetCustomAttributes(false); 
foreach(PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
  object[] propertyAttributes = property.GetCustomAttributes(false); 
  Console.WriteLine(property.Name);
}
Nitin Midha