C#
anonymous type
key/value array
type conversion
programming tips

In c convert anonymous type into key/value array?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In C#, an anonymous type is still a real object with named properties, but you cannot refer to its generated type name directly outside the local context. If you need a key/value representation, the usual approach is to reflect over its properties and convert them into a Dictionary, a KeyValuePair[], or another structure that downstream code can handle generically.

Anonymous Types Are Read-Only Property Bags

An anonymous type is typically created like this:

csharp
var person = new { Name = "Alice", Age = 30, Active = true };

The compiler generates a concrete type behind the scenes with read-only properties. You can use those properties normally inside the same scope, but if your next step is generic processing, you often want a key/value representation instead of the hidden generated type.

A KeyValuePair<string, object>[] is a common destination because it preserves both the property name and the value.

Convert an Object to Key/Value Pairs With Reflection

The most direct solution is to inspect the public properties and project them into key/value pairs.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Reflection;
5
6public static class ObjectExtensions
7{
8    public static KeyValuePair<string, object?>[] ToKeyValueArray(object value)
9    {
10        return value
11            .GetType()
12            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
13            .Select(p => new KeyValuePair<string, object?>(p.Name, p.GetValue(value)))
14            .ToArray();
15    }
16}
17
18class Program
19{
20    static void Main()
21    {
22        var person = new { Name = "Alice", Age = 30, Active = true };
23        var pairs = ObjectExtensions.ToKeyValueArray(person);
24
25        foreach (var pair in pairs)
26        {
27            Console.WriteLine($"{pair.Key}: {pair.Value}");
28        }
29    }
30}

This works for anonymous types, regular classes, and records because the code only cares about public properties.

Use a Dictionary When Lookup Matters More Than Order

If the consumer needs fast lookup by property name, convert to a dictionary instead.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public static class ObjectExtensions
6{
7    public static Dictionary<string, object?> ToDictionary(object value)
8    {
9        return value
10            .GetType()
11            .GetProperties()
12            .ToDictionary(p => p.Name, p => p.GetValue(value));
13    }
14}

That is often the better choice when you want to serialize, log, or enrich values by property name. If you specifically need an array, you can always call .ToArray() on the dictionary later.

Know the Limits of Reflection-Based Conversion

Reflection is flexible, but it has tradeoffs:

  • it is slower than direct property access
  • it only sees properties, not private fields
  • nested anonymous objects remain nested objects unless you flatten them manually
  • 'null values need to be handled by the consumer'

For one-off transformations, reflection is perfectly reasonable. If the conversion sits on a hot path, or if the shape is known in advance, an explicit projection is often better.

For example, if you already know the fields you want:

csharp
1var person = new { Name = "Alice", Age = 30, Active = true };
2
3var pairs = new[]
4{
5    new KeyValuePair<string, object?>("Name", person.Name),
6    new KeyValuePair<string, object?>("Age", person.Age),
7    new KeyValuePair<string, object?>("Active", person.Active)
8};

That version is faster and compile-time safe, but it only works when you already know the property names.

Prefer the Destination Structure That Matches the Next Step

The right target type depends on what happens next.

  • Use KeyValuePair<string, object>[] if a downstream API expects an ordered array of pairs.
  • Use Dictionary<string, object?> if name-based lookup matters.
  • Use a custom DTO if the shape is stable and part of your application contract.

That last option is often the cleanest design. If the object is important enough to travel between layers, an explicit type is usually easier to maintain than an anonymous type plus reflective conversion.

Common Pitfalls

  • Expecting the anonymous type itself to behave like a dictionary does not work. It is an object with properties, not a key/value collection.
  • Forgetting that reflection returns object values means consumers may still need casting or null handling.
  • Using reflection on performance-critical paths can become expensive if the conversion is repeated heavily.
  • Assuming nested anonymous objects will flatten automatically leads to confusing output. Reflection only reads the top-level property values unless you recurse intentionally.
  • Reaching for anonymous types when a stable DTO would be clearer can make the code harder to maintain over time.

Summary

  • Anonymous types can be converted to key/value arrays by reflecting over their public properties.
  • 'KeyValuePair<string, object?>[] and Dictionary<string, object?> are both reasonable targets.'
  • Reflection is the generic answer, while explicit projection is better when the shape is already known.
  • Choose the destination structure based on how the data will be consumed next.
  • If the shape is part of your program contract, prefer a named type over anonymous data plus reflection.

Course illustration
Course illustration

All Rights Reserved.