Skip to Content
All posts

Unleashing the Power of ExpandoObject in C#

3 min read ·  — #csharp-interview#senior#expando-object

Unleashing the Power of ExpandoObject in C#

Title: : A Deep Dive for Senior Software Engineers

Introduction: In the realm of dynamic objects and runtime object manipulation, ExpandoObject in C# stands as a testament to the language’s versatility and adaptability. As a Senior Software Engineer, harnessing the nuanced capabilities of ExpandoObject can substantially elevate your coding prowess, allowing for a more flexible and dynamic approach in handling data structures. This post aims to unravel the intricacies of ExpandoObject, diving deep into its practical applications and how it can be a game-changer in crafting solutions for complex, real-world scenarios. Whether you are preparing for a technical interview or just looking to refine your knowledge, join us as we explore the myriad possibilities with ExpandoObject, backed by concrete examples and best practices.


1. Understanding ExpandoObject:

ExpandoObject belongs to the System.Dynamic namespace and allows dynamic binding, enabling the addition and deletion of its members at runtime. This class is particularly useful when you need a flexible object whose structure is not known until runtime.

Example 1: Basic Usage

dynamic expando = new ExpandoObject();
expando.Name = "John Doe";
expando.Age = 30;
Console.WriteLine($"{expando.Name}, Age: {expando.Age}");

2. Adding/Removing Properties and Methods Dynamically:

With ExpandoObject, you can seamlessly add or remove properties and methods on the fly, making it invaluable for scenarios like parsing JSON or XML where the structure is unpredictable.

Example 2: Dynamic Member Addition/Removal

dynamic expando = new ExpandoObject();

expando.AddProperty = new Action<string, object>((name, value) =>
                  ((IDictionary<string, object>)expando).Add(name, value));

expando.RemoveProperty = new Action<string>(name =>
                  ((IDictionary<string, object>)expando).Remove(name));

expando.AddProperty("Language", "C#");
Console.WriteLine(expando.Language); // Output: C#

expando.RemoveProperty("Language");
Console.WriteLine(expando.Language); // RuntimeBinderException

3. Event Handling:

ExpandoObject supports event handling, which can be particularly useful for managing events in a loosely coupled manner, ideal for implementing plugins or handling UI events in a dynamic environment.

Example 3: Dynamic Event Handling

dynamic expando = new ExpandoObject();
expando.SampleEvent = null;

expando.SampleEvent += new EventHandler((sender, eventArgs) =>
                  Console.WriteLine("Sample Event Triggered!"));

((INotifyPropertyChanged)expando).PropertyChanged += (sender, eventArgs) =>
          Console.WriteLine($"Property Changed: {eventArgs.PropertyName}");

expando.SampleEvent(expando, EventArgs.Empty);
// Output: Sample Event Triggered!

4. Interacting with LINQ:

Leveraging ExpandoObject with LINQ can bring forth powerful querying capabilities, especially when dealing with collections of dynamic objects.

Example 4: LINQ Interaction

dynamic expando1 = new ExpandoObject();
expando1.Name = "John";
expando1.Age = 30;

dynamic expando2 = new ExpandoObject();
expando2.Name = "Jane";
expando2.Age = 25;

var people = new List<dynamic> { expando1, expando2 };
var youngPeople = people.Where(p => p.Age < 30);

foreach (var person in youngPeople)
{
    Console.WriteLine(person.Name); // Output: Jane
}

5. Real-world Scenario – Configuring Middleware:

Imagine a scenario where you are designing a middleware component, and you want to allow users to configure it dynamically. ExpandoObject can be a handy tool for storing configuration settings.

Example 5: Dynamic Middleware Configuration

dynamic middlewareConfig = new ExpandoObject();
middlewareConfig.UseLogging = true;
middlewareConfig.UseCaching = false;
middlewareConfig.Timeout = 3000;

ConfigureMiddleware(middlewareConfig);

void ConfigureMiddleware(dynamic config)
{
    if (config.UseLogging) { /* Configure logging */ }
    if (config.UseCaching) { /* Configure caching */ }
    // Set timeout
}

Conclusion:

By mastering the use of ExpandoObject in C#, Senior Software Engineers can employ a more dynamic and adaptable coding strategy, handling unforeseen challenges with grace and efficiency. As we have seen through various examples, whether it is manipulating object members at runtime, managing events, interacting with LINQ, or configuring middleware, ExpandoObject proves to be an invaluable asset in a developer's toolkit.

References: