ExpandoObject and Dynamic Programming in c# 4.0

ExpandoObject is a powerful tool available in both JavaScript and C# for creating dynamic objects with the ability to add and remove properties, methods, and events at runtime. In this blog post, we’ll delve into the usage of ExpandoObject in both languages, showcasing its versatility through practical examples.

Dynamic in C#

C# introduces the dynamic keyword, allowing developers to declare variables with types resolved at runtime. This flexibility brings several key characteristics to the language.

Key Characteristics of dynamic:

  1. Late Binding: Type resolution occurs at runtime, enabling late binding and deferring type checking until this phase.

  2. Dynamic Dispatch: Calls to dynamic object members are resolved at runtime, facilitating dynamic dispatch based on the actual object type.

  3. No Compile-Time Checking: Compile-time type checking is not performed for dynamic variables, leading to potential type-related errors surfacing only at runtime.

Example Using dynamic:

dynamic dynamicVariable = 10;
Console.WriteLine(dynamicVariable); // Outputs: 10

dynamicVariable = "Hello, Dynamic!";
Console.WriteLine(dynamicVariable); // Outputs: Hello, Dynamic!

In this example, dynamicVariable dynamically changes its type from int to string at runtime.

ExpandoObject in C#

ExpandoObject is part of the System.Dynamic namespace in C# and enables the creation of objects with dynamically added members.

Key Characteristics of ExpandoObject:

  1. Dynamic Member Addition: ExpandoObject allows for the dynamic addition of properties, methods, and events at runtime.

  2. No Explicit Class Definition: There’s no need to define a class structure in advance; members can be added dynamically.

Example Using ExpandoObject:

using System;
using System.Dynamic;

class Program
{
    static void Main()
    {
        dynamic dynamicObject = new ExpandoObject();
        dynamicObject.Name = "John";
        dynamicObject.Age = 25;

        Console.WriteLine($"{dynamicObject.Name} is {dynamicObject.Age} years old.");
    }
}

In this example, a dynamic object (dynamicObject) is created using ExpandoObject, and properties like Name and Age are dynamically added.

Dynamic Object Creation in JavaScript

function GetCustomer() {
    // Creating a dynamic customer object in JavaScript
    var customer = new Object();
    customer.City = "Gurgaon";
    customer.Country = "India";

    // Adding a dynamic method to get the full address
    customer.FullAddress = function () {
        return `${this.City}, ${this.Country}`;
    }

    // Invoking the dynamic method and displaying an alert
    alert(customer.FullAddress());
}

Here in JavaScript, a dynamic object named customer is created, and properties like City and Country are added. Additionally, a dynamic method, FullAddress, is attached to retrieve and display the full address.

Dynamic Object Creation in C# - A Comparison

using System;
using System.Dynamic;

namespace CSharpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a dynamic customer object
            dynamic customer = new ExpandoObject();
            customer.City = "Gurgaon";
            customer.Country = "India";

            // Adding a dynamic method to print the full address
            customer.FullAddress = new Action(() => Console.WriteLine(
                $"{customer.City}, {customer.Country}"
            ));

            // Invoking the dynamic method
            customer.FullAddress();
            
            Console.ReadKey();
        }
    }
}

In the C# counterpart, we achieve similar functionality using ExpandoObject. An ExpandoObject named customer is instantiated, and properties like City and Country are dynamically added. A dynamic method, FullAddress, is attached to print the full address when invoked.

Both dynamic and ExpandoObject empower developers in C# to write adaptable and flexible code, particularly in scenarios where types or structures are not known until runtime. Similarly, in JavaScript, dynamic object creation allows for the same flexibility, making it easier to adapt to changing requirements. However, it’s crucial to use these features judiciously, considering the trade-offs in terms of compile-time safety.

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru