C#
object properties
enumeration
programming
strings

Enumerating through an object's properties string in C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C#, the usual way to walk through an object's properties at runtime is reflection. That is useful when you need generic logging, debugging output, export code, or a simple inspection tool without hard-coding every property name.

Using Reflection to Read Properties

Every .NET object exposes its runtime type through GetType(). From that type you can ask for PropertyInfo objects and then read each property name and value. For most diagnostics code, you want public instance properties only.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Reflection;
5
6public sealed class Person
7{
8    public string Name { get; init; } = "";
9    public int Age { get; init; }
10    public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
11    public string this[int index] => $"item-{index}";
12}
13
14public static class ObjectPrinter
15{
16    public static IEnumerable<string> Describe(object value)
17    {
18        if (value is null)
19        {
20            throw new ArgumentNullException(nameof(value));
21        }
22
23        return value.GetType()
24            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
25            .Where(property => property.GetIndexParameters().Length == 0)
26            .Select(property =>
27                $"{property.Name} = {FormatValue(property.GetValue(value))}");
28    }
29
30    private static string FormatValue(object? value) =>
31        value switch
32        {
33            null => "(null)",
34            DateTime dateTime => dateTime.ToString("O"),
35            _ => value.ToString() ?? "(null)"
36        };
37}
38
39var person = new Person { Name = "Rita", Age = 32 };
40
41foreach (var line in ObjectPrinter.Describe(person))
42{
43    Console.WriteLine(line);
44}

This pattern gives you a list such as Name = Rita and Age = 32. The Where clause matters because indexer properties look like normal properties in reflection, but they require parameters and will throw if you call GetValue without arguments.

Controlling What Gets Enumerated

Reflection is flexible, but you should decide up front what counts as a property worth printing. In production code, common filters include public-only access, excluding indexers, skipping properties with expensive getters, or selecting properties marked with an attribute.

If you want only the property names as strings, you can project just the Name field.

csharp
1using System;
2using System.Linq;
3using System.Reflection;
4
5public static class PropertyNames
6{
7    public static string[] GetNames<T>()
8    {
9        return typeof(T)
10            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
11            .Where(property => property.GetIndexParameters().Length == 0)
12            .Select(property => property.Name)
13            .ToArray();
14    }
15}
16
17foreach (var name in PropertyNames.GetNames<Person>())
18{
19    Console.WriteLine(name);
20}

That is often enough when you need headers for CSV output, dynamic mapping, or a generic user interface.

Formatting Values Safely

The property value is returned as object, so formatting is your responsibility. Primitive types are simple, but dates, nullable values, and nested objects benefit from explicit handling. A raw call to ToString() can produce culture-dependent or unhelpful output.

For logs or exported text, prefer stable formatting rules. For example, use the round-trip format string for DateTime, output (null) for missing values, and think carefully before recursing into complex child objects. Unlimited recursion can explode into unreadable output or circular references.

Another practical point is side effects. Reflection only reads metadata safely; getters themselves may still run real code. If a property performs lazy loading, hits a database, or throws when a dependency is missing, enumeration may fail. Reflection is not a guarantee that property access is cheap.

When Reflection Is the Right Tool

Reflection is appropriate when the set of properties is not known at compile time. Examples include audit logging, object inspection in tests, admin utilities, and building generic serializers. If you already know the exact properties you need, direct property access is faster, simpler, and easier to refactor.

In performance-sensitive paths, cache the PropertyInfo[] array instead of calling GetProperties() repeatedly. Reflection is fast enough for many tools, but repeated metadata discovery inside a tight loop adds overhead you can avoid.

Common Pitfalls

  • Calling GetValue on an indexer property without parameters throws at runtime, so filter out properties where GetIndexParameters().Length is not zero.
  • Assuming every getter is cheap is risky because some properties execute real logic or lazy-load data.
  • Using reflection in a hot loop without caching metadata creates avoidable overhead.
  • Relying on ToString() for every type can produce unstable or unhelpful output, especially for dates and nested objects.
  • Forgetting binding flags can change the result set, leading to confusion about missing or extra properties.

Summary

  • Reflection is the standard C# technique for enumerating an object's properties at runtime.
  • 'GetProperties plus PropertyInfo.GetValue lets you turn properties into readable strings.'
  • Filtering indexers and formatting values explicitly makes the output safer and more useful.
  • Reflection is best for generic tooling, not for code paths where the schema is already known.
  • Cache metadata when repeated enumeration matters for performance.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.