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.
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.
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.
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
GetValueon an indexer property without parameters throws at runtime, so filter out properties whereGetIndexParameters().Lengthis 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.
- '
GetPropertiesplusPropertyInfo.GetValuelets 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
- Environment.GetFolderPath...CommonApplicationData is still returning CDocuments and Settings on Vista
- Environment.TickCount vs DateTime.Now
- EPPlus number format
- Equivalent of Ihostedservice in asp.net framework for background tasks
- Equivalent to 'app.config' for a library DLL
- Equivalent to C's using keyword in powershell?
- Error - The transaction associated with the current connection has completed but has not been disposed
- Error CS1705 which has a higher version than referenced assembly

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.