Overview
Dynamic binding defers type checking and member resolution from compile time to runtime. This feature proves invaluable when working with COM objects, IronPython libraries, HTML DOM, or any scenario where type information remains unknown until exeuction time.
Key Characteristics
Deferred Type Resolution
dynamic configuration = LoadConfiguration();
configuration.Initialize();
The compiler bypasses type validation for configuration. Method existence and parameter compatibility get verified at runtime instead.
Runtime Member Invocation
dynamic data = FetchDataSource();
var processed = data.Transform(inputValue, options);
Method names resolve dynamically, enabling invocation of methods that may not exist on any compile-time type.
Runtime Type Conversion
dynamic source = GetData();
string text = (string)source;
double[] metrics = (double[])source;
Type conversions execute during runtime, with the runtime performing necessary compatibility checks.
Runtime Object Instantiation
dynamic instance = Activator.CreateInstance(targetType);
instance.Execute(task, configuration);
Objects instantiate based on types determined at runtime, allowing flexible instantiation patterns.
Practical Applications
Accessing Type Members via Reflection
using System;
using System.Reflection;
class Employee
{
public string FullName { get; set; }
public int Identification { get; set; }
}
class Demonstration
{
static void Main()
{
Type employeeType = typeof(Employee);
PropertyInfo nameInfo = employeeType.GetProperty("FullName");
PropertyInfo idInfo = employeeType.GetProperty("Identification");
var staff = new Employee();
nameInfo.SetValue(staff, "Alice");
idInfo.SetValue(staff, 42);
Console.WriteLine($"Employee: {staff.FullName}, ID: {staff.Identification}");
}
}
Creating Instances Dynamically
using System;
class Product
{
public string Description { get; set; }
public decimal Price { get; set; }
}
class Demonstration
{
static void Main()
{
var item = Activator.CreateInstance<Product>();
item.Description = "Wireless Keyboard";
item.Price = 49.99m;
Console.WriteLine($"{item.Description} costs {item.Price:C}");
}
}
Invoking Methods Dynamically
using System;
using System.Reflection;
class ArithmeticOperations
{
public int Multiply(int x, int y) => x * y;
public int Divide(int x, int y) => x / y;
}
class Demonstration
{
static void Main()
{
var operations = new ArithmeticOperations();
MethodInfo multiplyInfo = operations.GetType().GetMethod("Multiply");
int product = (int)multiplyInfo.Invoke(operations, new object[] { 7, 6 });
Console.WriteLine(product);
MethodInfo divideInfo = operations.GetType().GetMethod("Divide");
int quotient = (int)divideInfo.Invoke(operations, new object[] { 20, 4 });
Console.WriteLine(quotient);
}
}