Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

ExpandoObject — an object with a changeable set of members

ExpandoObject in System.Dynamic lets you add and remove members at run time. It supports access through dynamic and through the IDictionary<string, object?> dictionary interface.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

dynamic item = new ExpandoObject();
item.Name = "Ada";
var members = (IDictionary<string, object?>)item;
members.Remove("Name");

ExpandoObject in System.Dynamic stores members added at run time. Assigning item.Name = "Ada" through dynamic adds a named entry; a later assignment updates its value.

dynamic defers operation checking until execution. In contrast, var item = new ExpandoObject() gives the variable the static type ExpandoObject, so it does not directly allow item.Name. A typo in a dynamic read or reading a removed member causes a run-time error rather than a compilation error.

Casting to IDictionary<string, object?> exposes the same data through string keys. ContainsKey and TryGetValue let you check whether an entry exists; Remove deletes it. Assigning null does not remove the key.

The example updates Score through the dictionary, reads the result through dynamic, and then removes Name. For a fixed schema, prefer a class or record: the compiler can then check member names and types.

Examples

using System;
using System.Collections.Generic;
using System.Dynamic;

dynamic item = new ExpandoObject();
item.Name = "Ada";
item.Score = 7;

var members = (IDictionary<string, object?>)item;
members["Score"] = 8;
Console.WriteLine($"{item.Name}: {item.Score}");

members.Remove("Name");
Console.WriteLine(members.ContainsKey("Name") ? "present" : "missing");

Result

Ada: 8
missing

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources