JavaScript
Object Properties
DateTime
Looping
Programming Techniques

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.

csharp
1using System;
2using System.Collections.Generic;
3using System.Reflection;
4
5public static class DateReader
6{
7    public static IEnumerable<(string Name, object? Value)> GetDateProperties(object obj)
8    {
9        foreach (var property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
10        {
11            var effectiveType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
12            if (effectiveType == typeof(DateTime))
13            {
14                yield return (property.Name, property.GetValue(obj));
15            }
16        }
17    }
18}

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.

csharp
1using System;
2
3public class Order
4{
5    public int Id { get; set; }
6    public DateTime CreatedAt { get; set; }
7    public DateTime? ShippedAt { get; set; }
8    public string CustomerName { get; set; } = "";
9}
10
11public class Program
12{
13    public static void Main()
14    {
15        var order = new Order
16        {
17            Id = 10,
18            CreatedAt = new DateTime(2026, 3, 11, 9, 0, 0),
19            ShippedAt = null,
20            CustomerName = "Ana"
21        };
22
23        foreach (var item in DateReader.GetDateProperties(order))
24        {
25            Console.WriteLine($"{item.Name}: {item.Value}");
26        }
27    }
28}

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:

csharp
1var value = property.GetValue(obj);
2if (effectiveType == typeof(DateTime) && value != null)
3{
4    yield return (property.Name, value);
5}

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.

csharp
1using System;
2using System.Collections.Generic;
3using System.Reflection;
4
5public static class DeepDateReader
6{
7    public static void Walk(object? obj, string prefix, List<(string Path, DateTime Value)> output)
8    {
9        if (obj == null) return;
10
11        if (obj is DateTime dt)
12        {
13            output.Add((prefix, dt));
14            return;
15        }
16
17        var type = obj.GetType();
18        if (type.IsPrimitive || obj is string) return;
19
20        foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
21        {
22            var value = property.GetValue(obj);
23            var path = string.IsNullOrEmpty(prefix) ? property.Name : $"{prefix}.{property.Name}";
24            Walk(value, path, output);
25        }
26    }
27}

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 forgetting DateTime?.
  • 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 DateTime and DateTime? 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.

Course illustration
Course illustration

All Rights Reserved.