ExpandoObject:  C# Feel Like JavaScript

ExpandoObject: C# Feel Like JavaScript

In the world of C#, where strong typing and compile-time safety are key, there are times when you need the flexibility of dynamic objects. Enter ExpandoObject, a powerful feature that allows you to create objects with dynamic properties and methods at runtime. In this blog, we’ll explore what ExpandoObject is, how it compares to the dynamic keyword, its JavaScript-like features, and how to add properties and functions dynamically.

What is ExpandoObject in C#?

ExpandoObject is a class in C# that allows you to create objects whose members (properties, methods, etc.) can be added, removed, or modified at runtime. It is part of the System.Dynamic namespace and is particularly useful when working with data structures that are not known at compile time.

Key Features of ExpandoObject:

  • Dynamic Properties: Add or remove properties at runtime.

  • Dynamic Methods: Add methods dynamically.

  • Dictionary-Like Behavior: Implements IDictionary<string, object>, so you can use it like a dictionary.

  • JavaScript-Like Flexibility: Feels similar to working with objects in JavaScript.

Dynamic vs ExpandoObject:

dynamic Keyword

  • The dynamic keyword allows you to bypass compile-time type checking. The type is resolved at runtime.

  • It can be used with any object, but it doesn’t provide the ability to add or remove members dynamically.

ExpandoObject

  • ExpandoObject is a specific class designed for dynamic objects.

  • It allows you to add, remove, or modify properties and methods at runtime.

When to Use:

  • Use dynamic when you need to work with objects whose types are unknown at compile time.

  • Use ExpandoObject when you need to create objects with dynamic members.

JavaScript-Like Features

ExpandoObject brings JavaScript-like flexibility to C#. Here’s how:

  • Dynamic Properties: Add properties to an object at runtime, just like in JavaScript.

  • Dynamic Methods: Add methods to an object at runtime.

  • Dictionary-Like Access: Use ExpandoObject as a dictionary to manipulate properties.

using System.Dynamic;

//Adding Properties
dynamic person = new ExpandoObject();
person.FirstName = "John";
person.LastName = "Doe";
person.Age = 30;
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");// Output: "John Doe, Age: 30"

//Adding Functions
person.Greet = new Action(() => {
    Console.WriteLine($"Hello, {person.FirstName} {person.LastName}!");
});
person.Greet(); // Output: "Hello, John Doe!"

//Using Dictionary Syntax
var personDict = (IDictionary<string, object>)person;
// Add a property
personDict["Email"] = "john.doe@example.com";
// Add a method
personDict["Introduce"] = new Action(() => {
    Console.WriteLine($"I'm {person.FirstName} {person.LastName}, and my email is {person.Email}.");
});
person.Introduce(); // Output: "I'm John Doe, and my email is john.doe@example.com."

Practical Use Cases:

  1. Working with Dynamic Data: When dealing with JSON or other dynamic data structures, ExpandoObject can be used to parse and manipulate the data.

  2. Runtime Configuration: Create configuration objects where properties are added or removed based on runtime conditions.

  3. Prototyping: Quickly prototype objects without defining a class.

  4. Interoperability: Interact with APIs or libraries that require dynamic objects.

Example: Dynamic JSON Parsing:

Here’s an example of using ExpandoObject to parse and manipulate JSON data dynamically:

using System.Dynamic;
using System.Text.Json;


string json = @"
{
    ""FirstName"": ""John"",
    ""LastName"": ""Doe"",
    ""Age"": 30
}";

// Parse JSON into ExpandoObject
dynamic person = JsonSerializer.Deserialize<ExpandoObject>(json)!;

// Access properties
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");

// Add a new property
person.Email = "john.doe@example.com";

// Add a method
person.Introduce = new Action(() => {
    Console.WriteLine($"I'm {person.FirstName} {person.LastName}, and my email is {person.Email}.");
});
person.Introduce();

ExpandoObject is a powerful tool in C# that brings JavaScript-like flexibility to a strongly-typed language. Whether you’re working with dynamic data, runtime configurations, or prototyping, ExpandoObject allows you to add properties and methods dynamically, making your code more adaptable and expressive.

By leveraging ExpandoObject, you can handle scenarios where the structure of your data is not known at compile time, all while maintaining the power and safety of C#.

Happy coding!