C# -

Dynamic Types

Dynamic types in C# allow you to bypass compile-time type checking. This feature is useful when working with dynamically typed languages or when you need more flexibility in your code. This tutorial covers the basics, use cases, and advanced concepts of dynamic types.


1. Introduction to Dynamic Types

The `dynamic` keyword in C# allows variables to be dynamically typed, meaning their type is resolved at runtime. This provides flexibility but comes with the cost of losing compile-time type checking.

        
            using System;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        dynamic variable = 1;
        Console.WriteLine(variable);

        variable = "Hello";
        Console.WriteLine(variable);

        variable = DateTime.Now;
        Console.WriteLine(variable);
    }
}
        
    

2. Using Dynamic Variables

You can declare a variable as `dynamic` and assign different types of values to it. Here’s how to use dynamic variables:

        
            using System;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        dynamic value = 10;
        Console.WriteLine($"Value: {value}, Type: {value.GetType()}");

        value = "Dynamic Type";
        Console.WriteLine($"Value: {value}, Type: {value.GetType()}");

        value = DateTime.Now;
        Console.WriteLine($"Value: {value}, Type: {value.GetType()}");
    }
}
        
    

3. Dynamic and Reflection

The dynamic type can work seamlessly with reflection, allowing you to invoke members dynamically. Here’s an example:

        
            using System;
using System.Reflection;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        dynamic obj = new ExampleClass();
        Console.WriteLine(obj.DynamicMethod("Hello"));

        MethodInfo method = obj.GetType().GetMethod("DynamicMethod");
        Console.WriteLine(method.Invoke(obj, new object[] { "Reflection" }));
    }
}

public class ExampleClass
{
    public string DynamicMethod(string input)
    {
        return $"Input was: {input}";
    }
}
        
    

4. Interoperability with COM Objects

Dynamic types are particularly useful when working with COM objects, as they allow you to call methods and properties without needing interop assemblies. Here’s an example:

        
            using System;
using Microsoft.Office.Interop.Excel;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        Application excelApp = new Application();
        excelApp.Visible = true;
        Workbook workbook = excelApp.Workbooks.Add();
        Worksheet worksheet = workbook.Worksheets[1];
        
        dynamic cell = worksheet.Cells[1, 1];
        cell.Value = "Dynamic COM Interop";
        
        workbook.SaveAs(@"C:\Temp\DynamicInterop.xlsx");
        workbook.Close();
        excelApp.Quit();
    }
}
        
    

5. Dynamic Types in ASP.NET MVC

ASP.NET MVC makes extensive use of dynamic types, especially in view models. Here’s how to use dynamic types in an ASP.NET MVC project:

        
            using System.Web.Mvc;

namespace DynamicTypesExamples;

public class HomeController : Controller
{
    public ActionResult Index()
    {
        dynamic model = new ExpandoObject();
        model.Message = "Hello, Dynamic World!";
        return View(model);
    }
}
        
    

6. Dynamic Types and JSON

Parsing JSON data into dynamic objects can simplify data handling. Here’s an example of working with JSON data dynamically:

        
            using System;
using Newtonsoft.Json;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        string json = "{ 'Name': 'John', 'Age': 30 }";
        dynamic person = JsonConvert.DeserializeObject(json);
        
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
    }
}
        
    

7. Dynamic Object

The `DynamicObject` class allows you to create objects that can have dynamic members. Here’s how to create and use a dynamic object:

        
            using System;
using System.Dynamic;

namespace DynamicTypesExamples;

public class DynamicDictionary : DynamicObject
{
    private readonly Dictionary<string, object> _dictionary = new Dictionary<string, object>();

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return _dictionary.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        _dictionary[binder.Name] = value;
        return true;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        dynamic obj = new DynamicDictionary();
        obj.Name = "Dynamic Dictionary";
        Console.WriteLine(obj.Name);
    }
}
        
    

8. ExpandoObject

The `ExpandoObject` class allows you to add and remove members at runtime. Here’s an example of using `ExpandoObject`:

        
            using System;
using System.Dynamic;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        dynamic obj = new ExpandoObject();
        obj.Name = "Expando Object";
        obj.Display = new Action(() => Console.WriteLine(obj.Name));
        
        obj.Display();
    }
}
        
    

9. Dynamic LINQ

Dynamic LINQ allows you to create LINQ queries dynamically. Here’s how to use dynamic LINQ:

        
            using System;
using System.Linq.Dynamic.Core;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var data = new[] { 1, 2, 3, 4, 5 };
        var query = data.AsQueryable().Where("it > 2");
        
        foreach (var item in query)
        {
            Console.WriteLine(item);
        }
    }
}
        
    

10. Dynamic and Inheritance

Dynamic types can be used in inheritance scenarios to create flexible and extensible code. Here’s an example:

        
            using System;

namespace DynamicTypesExamples;

public class BaseClass
{
    public virtual dynamic DynamicMethod(dynamic input)
    {
        return input;
    }
}

public class DerivedClass : BaseClass
{
    public override dynamic DynamicMethod(dynamic input)
    {
        return $"Derived: {input}";
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        BaseClass obj = new DerivedClass();
        Console.WriteLine(obj.DynamicMethod("Test"));
    }
}
        
    

11. Dynamic and Generics

You can combine dynamic types with generics to achieve more flexible type handling. Here’s an example:

        
            using System;

namespace DynamicTypesExamples;

public class GenericClass<T>
{
    public dynamic GenericMethod(dynamic input)
    {
        return $"Generic: {input}";
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var obj = new GenericClass<int>();
        Console.WriteLine(obj.GenericMethod("Test"));
    }
}
        
    

12. Performance Considerations

Using dynamic types can impact performance because type resolution happens at runtime. Here are some performance considerations when using dynamic types:

        
            using System;
using System.Diagnostics;

namespace DynamicTypesExamples;

public class Program
{
    public static void Main(string[] args)
    {
        dynamic value = 10;
        var sw = Stopwatch.StartNew();

        for (int i = 0; i < 1000000; i++)
        {
            value += 1;
        }

        sw.Stop();
        Console.WriteLine($"Dynamic: {sw.ElapsedMilliseconds} ms");

        int staticValue = 10;
        sw.Restart();

        for (int i = 0; i < 1000000; i++)
        {
            staticValue += 1;
        }

        sw.Stop();
        Console.WriteLine($"Static: {sw.ElapsedMilliseconds} ms");
    }
}
        
    


13. Conclusion

Dynamic types are a powerful feature in C# that provide flexibility in handling types at runtime. By understanding how to use dynamic types effectively, you can create more versatile and adaptable applications. This tutorial covered the basics, use cases, and best practices for using dynamic types.