I would recommend using a custom ToString() override, as the other posts
suggested.
But since you asked for a reflection solution and said you couldn't
figure it out, I'll give you an example. This is just to show you how to
do it - this isn't the solution I would recommend in most cases (but
maybe it fits for your scenario).
public class SomeClass
{
public string var1 = "theVar1";
public int var2 = 42;
public DateTime var3 = DateTime.Now;
public object[] GetAllVariablesAsArray()
{
FieldInfo[] fields =
this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.DeclaredOnly);
// Note - use PropertyInfo and GetProperties() if your values are stored
in properties instead of fields
object[] variables = new object[fields.Length];
for (int i = 0; i < fields.Length; i++)
{
variables[i] = fields[i].GetValue(this);
}
return variables;
}
}
An example of using the method would be:
class Program
{
static void Main(string[] args)
{
SomeClass sc = new SomeClass();
foreach (object var in sc.GetAllVariablesAsArray())
{
Console.WriteLine(var.ToString());
}
}
}
Hope this helps.
Joshua Flanagan
http://flimflan.com/blog
Daan wrote:
Say I have an Object of the following class:
public class SomeClass {
public string var1;
public int var2;
public SomeType var3;
}
Now I want to print all the three vars. Is it possible to get an array
containing these three vars, making something like this possible:
for (int i = 0; i < myArray.Length; i++) {
myPrintFunction(myArray[i]);
}
Or is there no other option then to print each class variable
explicitly, like this:
myPrintFunction(myObject.var1);
myPrintFunction(myObject.var2);
myPrintFunction(myObject.var3);
My guess would be that the Reflection library makes such a thing
possible, but I could not find it there.
Regards,
Daan