tags:

views:

71

answers:

4

Is there a way to enumerate or simply for each into a class's member variables in .net ? I have a static class, which i want to use for holding the application settings, so while saving the settings I basically want to copy the values of the Static Class to a Instance of a class containg the same set of (non-static) variables .

SO i thought "if only I could foreach or even for() (for that matter..pun unintended) it would be easier

+2  A: 

You can use reflection. If obj is the object you want to look at:

foreach (FieldInfo fi in obj.GetType ().GetFields ()) 
    Console.WriteLine ("{0} : {1}", fi.Name, fi.GetValue (obj));

Likewise PropertyInfo to enumerate through properties.

Tarydon
This will only enumerate public fields, which may not be sufficient.
Lucero
+1  A: 

Sort of, by using reflection:

 instance.GetType().GetFields(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);

This does have some limitations, though, such as the security requirement for reflection.

Lucero
A: 

Perhaps you are looking for the Type.GetFields method.

Kaleb Brasee
+1  A: 

from your description, Dictionary would be a good data type to store your application settings:

Dictionary<string, string> settings = new Dictionary<string, string>();
settings["key1"] = "value";
settings["key2"] = "value";

Dictionary<string, string> copy = new Dictionary<string, string>(settings);
copy["key1"] = "override value";
foreach (KeyValuePair<string, string> kv in copy) {
  Console.WriteLine("Key {0} has value {1}", kv.Key, kv.Value);
}

a more low-level thing would be to use reflection to retrieve the class's members or fields:

foreach (MemberInfo mi in Type.GetType(MyClass).GetMembers()) {
  Console.WriteLine("Member {0} has type {1}",
    mi.Name, mi.MemberType().ToString());
}
jspcal
So..ok..I think i'll go with the Dictionary method, seems a lot easier. Anyway the reflection thing does look handy.
Vivek Bernard
Vivek: be sure to mark your accepted answer as such.
Matt Ellen