If you can't think of a good reason TO use dynamic, then you are foregoing potential compile time checks for little to nothing in return.
I prefer generics over object, and prefer object over dynamic, unless I need to interact with a dynamic language ScriptEngine or a dynamic container like a web form where its reasonable to handle the potential runtime exceptions when I access a missing field. Generics will perform best; and with object, you are at least signifying your intentions are to store any sort of object in the same container.
Dynamic is not an actual type, and it isn't "object" so it should never be used to mean "any sort of object", it should actually be used when you know what the object's contract is (method/property signature's); it is a runtime dispatch vehicle for keeping the same, convenient syntax for a type-unsafe (or at least dynamically bound) activity. It's like saying:
"OK, I know the activity I'm doing is subject to runtime dispatch and
runtime errors, so give me the syntactical sugar anyway"
When I see dynamic, I usually assume there is an imminent:
- method call dispatch to a dynamically bound type (like an IronPython variable)
- access to dynamic form data with property syntax in an MVC controller
Though another legit use for it is to use the dynamic dispatch capability to implement the Visitor Pattern
, although traditional virtual methods are likely faster.
class FooVisitor {
void Accept(Expression node) { ... }
void Accept(Statement node) { ... }
}
foreach(dynamic node in ASTNodes) {
visitor.Accept(obj); // will be dispatched at runtime based on type of each obj
}
Don't use it when:
- Performance is number one priority.
- Static type checking is desirable for more robust runtime
- The types can be derived at compile time
- A generic type will do
If used unnecessarily, dynamic can actually reduce the robustness of your code by changing C# to a dynamic scripting language.