In C#, the dynamic keyword is a type that represents an object whose operations will be resolved at runtime rather than at compile time.
dynamic dynamicVariable = 10; // Implicitly becomes an int
Console.WriteLine(dynamicVariable); // Outputs: 10
dynamicVariable = "Hello, Dynamic!"; // Implicitly becomes a string
Console.WriteLine(dynamicVariable); // Outputs: Hello, Dynamic!
Feature | dynamic | object |
---|---|---|
Type Checking | Resolved at runtime, no compile-time type checking | Compile-time type checking |
Implicit Typing | Type is determined implicitly at runtime | Explicitly declared type |
Late Binding | Yes | No |
Compile-Time Safety | Less safe due to deferred type checking | Compile-time safety ensured |
Method Invocation | Resolved at runtime, allows flexibility in method calls | Compile-time method invocation with explicit casting |
Property Access | Resolved at runtime, allows flexibility in property access | Compile-time property access with explicit casting |
Nullability | Can represent null | Can represent null |
Performance | Potentially slower due to runtime type resolution | Generally faster due to compile-time type resolution |