Loop through an object's properties and get the values for those of type DateTime
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
If you need to inspect an object's properties and pull out the ones of type DateTime, the practical answer is usually C# reflection. The pattern is to enumerate public instance properties, normalize nullable types, and read values only for properties whose underlying type is DateTime.
Start with a Simple Reflection Pass
For a flat object, reflection gives you the property metadata you need.
The key line is the nullable normalization. Without it, DateTime? properties are missed because their direct property type is Nullable<DateTime>, not DateTime.
Example Usage
A small example makes the pattern concrete.
This prints only the date-shaped properties. It ignores Id and CustomerName because their types do not match the filter.
Decide What to Do with Null Values
Sometimes you want to include nullable date properties even when their value is null, because the caller wants to know which properties are date-like. Other times you only want actual timestamps.
If you want only populated values, add a value check:
This is a policy decision, not just a syntax detail. A metadata-oriented tool and an export-oriented tool may reasonably choose different rules here.
Recursion Is a Separate Problem
The basic reflection pass sees only direct properties on the current object. If the object graph contains nested types, a deeper traversal is needed.
This is useful for auditing or export tools, but it introduces new concerns such as cyclic graphs, collections, and performance. Do not add recursion unless the problem really needs it.
Reflection Is Powerful but Not Free
Reflection is appropriate when the object type is not known until runtime or when you are building infrastructure code such as mappers, exporters, or generic validators. If the type is already known at compile time, direct property access is usually clearer and faster.
That is the practical test: use reflection when flexibility is the point, not when it is just habit.
Common Pitfalls
- Checking only for
typeof(DateTime)and forgettingDateTime?. - Using reflection when the object shape is already known and direct property access would be simpler.
- Assuming a flat scan also finds nested date properties.
- Failing to decide whether null
DateTime?values should be included. - Adding recursive traversal without guarding against cycles or large graphs.
Summary
- Use reflection to inspect public instance properties when the type is not known at compile time.
- Normalize nullable types so both
DateTimeandDateTime?can match. - Decide explicitly whether null date values should be included.
- Add recursion only if nested object traversal is actually required.
- Prefer direct property access when the class shape is already known.

