Letβs go through dynamic typing / dynamic programming in C# β a feature that allows runtime type flexibility.
π 1. What is dynamic
in C#?
-
The
dynamic
keyword allows variables to bypass compile-time type checking. -
Type is resolved at runtime, rather than at compile-time like normal types (
int
,string
, etc.). -
Useful when working with COM objects, reflection, JSON, or dynamic APIs.
π 2. Declaring Dynamic Variables
dynamic data = 10;
Console.WriteLine(data); // 10
data = "Hello";
Console.WriteLine(data); // Hello
data = DateTime.Now;
Console.WriteLine(data); // current date-time
-
Variable type changes at runtime
-
Compiler does not check method calls or property access
π 3. Dynamic vs Object
Feature | object | dynamic |
---|---|---|
Type Checking | Compile-time | Runtime |
Method Calls | Need casting | No casting needed |
Flexibility | Less flexible | Highly flexible |
Errors | Compile-time errors | Runtime errors if invalid |
Example:
object obj = 10;
// Console.WriteLine(obj + 5); // Compile-time error
dynamic dyn = 10;
Console.WriteLine(dyn + 5); // Works at runtime, output: 15
π 4. Using Dynamic in Methods
dynamic Add(dynamic a, dynamic b)
{
return a + b;
}
Console.WriteLine(Add(5, 10)); // 15
Console.WriteLine(Add("Hello ", "C#")); // Hello C#
- Works with any types that support the operation at runtime
π 5. Dynamic and Reflection / COM
-
dynamic
is commonly used when types are unknown at compile time, e.g., working with:-
COM objects (Excel, Word interop)
-
JSON or XML objects
-
Reflection-based method invocation
-
dynamic excelApp = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
excelApp.Visible = true;
π 6. Risks of dynamic
-
No compile-time checking β runtime errors
-
Performance overhead β runtime binding is slower
-
Should be used only when necessary, e.g., interacting with dynamic APIs
π 7. Summary Table
Feature | Description |
---|---|
Keyword | dynamic |
Type Checking | Runtime |
Flexibility | Can store any type |
Common Uses | COM, reflection, JSON, XML, runtime API calls |
Risks | Runtime errors, slower performance |
β Tip:
-
Use
dynamic
for runtime-flexible scenarios -
Avoid
dynamic
when compile-time type safety is important