What is ExpandoObject in C#?
ExpandoObject is a class in C# that provides a way to create objects with dynamic properties at runtime. It belongs to the System.Dynamic namespace. The name "ExpandoObject" is derived from "expandable object," indicating its ability to grow by dynamically adding properties and methods.
The ExpandoObject class implements the IDictionary<string, object> and ICollection<KeyValuePair<string, object>> interfaces, which allow it to behave like a dictionary or a collection of key-value pairs. It provides methods to add, remove, and access properties dynamically.
Once you have added properties to the ExpandoObject, you can access them just like taking things out of a bag. You can read the values of the properties or assign new values to them. It gives you the flexibility to work with data that might change or have an unknown structure.
Key Features of ExpandoObject in C#
Dynamic Property Addition: You can add properties to an ExpandoObject dynamically using the dot notation (expandoObject.PropertyName = value).
using System;
using System.Dynamic;
class Program
{
static void Main()
{
dynamic expandoObject = new ExpandoObject();
// Adding properties dynamically
expandoObject.Name = "John";
expandoObject.Age = 25;
// Adding a property with a custom getter
((IDictionary<string, object>)expandoObject).Add("FullName", "John Doe");
((IDictionary<string, object>)expandoObject).Add("Greeting", new Func<string>(() => $"Hello, {expandoObject.FullName}!"));
Console.WriteLine(expandoObject.Name);
Console.WriteLine(expandoObject.Age);
Console.WriteLine(expandoObject.FullName);
Console.WriteLine(expandoObject.Greeting());
}
}
Output

Dynamic Property Access: You can access the properties of an ExpandoObject dynamically using the dot notation (expandoObject.PropertyName).
using System;
using System.Dynamic;
class Program
{
static void Main()
{
dynamic employee = new ExpandoObject();
// Adding properties dynamically
employee.FirstName = "John";
employee.LastName = "Doe";
employee.Age = 30;
// Accessing properties dynamically
Console.WriteLine($"Employee: {employee.FirstName} {employee.LastName}");
Console.WriteLine($"Age: {employee.Age}");
// Adding and accessing nested properties dynamically
employee.Address = new ExpandoObject();
employee.Address.Street = "123 Main St";
employee.Address.City = "New York";
employee.Address.Country = "USA";
Console.WriteLine($"Address: {employee.Address.Street}, {employee.Address.City}, {employee.Address.Country}");
}
}




Ramesh PalanivelPosted Jun 26, 2023, 5:26 AM
Nice article.