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

Featureobjectdynamic
Type CheckingCompile-timeRuntime
Method CallsNeed castingNo casting needed
FlexibilityLess flexibleHighly flexible
ErrorsCompile-time errorsRuntime 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

  1. No compile-time checking β†’ runtime errors

  2. Performance overhead β†’ runtime binding is slower

  3. Should be used only when necessary, e.g., interacting with dynamic APIs


πŸ“Œ 7. Summary Table

FeatureDescription
Keyworddynamic
Type CheckingRuntime
FlexibilityCan store any type
Common UsesCOM, reflection, JSON, XML, runtime API calls
RisksRuntime errors, slower performance

βœ… Tip:

  • Use dynamic for runtime-flexible scenarios

  • Avoid dynamic when compile-time type safety is important