Sewder
Sewder

Reputation: 754

How to print all property values of an object without naming the properties explicitly

How do I iterate through the List<Galaxy> and print out the value(s) of every property without having to write the property name(s) explicitly?

For example, I use this code to write property values of all properties of galaxy

private static void IterateThroughList()
{
    var theGalaxies = new List<Galaxy>
    {
        new Galaxy() { Name = "Tadpole", MegaLightYears = 400},
        new Galaxy() { Name = "Pinwheel", MegaLightYears = 25}
    };

    foreach (Galaxy theGalaxy in theGalaxies) 
    {
        // this part is of concern
        Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears);
    }
}

I'm trying to avoid the explicit property names in this line

Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears);

So that, if my Galaxy class had more properties than Name and MegaLightYears, it would automatically print them too.

Upvotes: 3

Views: 12464

Answers (3)

Arghya C
Arghya C

Reputation: 10068

If you want to

  • Write all properties without naming them
  • Use it for any Type in a generic way

You can write a quick Reflection utility like this

public static string GetAllProperties(object obj)
{
    return string.Join(" ", obj.GetType()
                                .GetProperties()
                                .Select(prop => prop.GetValue(obj)));
}

And use it like

foreach (Galaxy theGalaxy in theGalaxies)
{
    Console.WriteLine(GetAllProperties(theGalaxy));
}

Upvotes: 7

Joey
Joey

Reputation: 354546

If I understand you correctly you want to avoid having to write the individual properties of the galaxy within the loop?

In that case you might overload ToString on Galaxy appropriately:

class Galaxy {
  public override string ToString() {
    return Name + "  " + MegaLightYearsl;
  }
}

Then you can just do

foreach (var galaxy in theGalaxies) {
  Console.WriteLine(galaxy);
}

However, since you only have one ToString to override, you cannot do this for wildly differing string representations of your object that may be needed in different contexts.

Upvotes: 4

M. Damian Mulligan
M. Damian Mulligan

Reputation: 869

Your question is a little unclear, but I assume you're asking for how you iterate through a list by index instead of as a foreach loop.

Try a standard for loop, like so:

for(int i = 0; i < theGalaxies.Count; i++) {
    Console.WriteLine(theGalaxies[i].Name + "  " + theGalaxies[i].MegaLightYears);
}

Upvotes: 0

Related Questions