Does "dynamic" keyword in C# work like "auto" in C++
More details:
auto a = 5; //C++
dynamic a = 5; //C#
Are they similar?
NO, they are not similar. AFAIK, auto
would be similar to var
in C#.
auto
gets resolved to compile time, not runtime.
FROM MSDN
The auto keyword directs the compiler to use the initialization expression of a declared variable to deduce its type.
So in your code
auto a = 5; //C++
a.ToUpper(); // Compile time error
But
dynamic a = 5; //C#
a.ToUpper(); //No error at compile time since it will resolve @ runtime
But at run time it will throw an error since int
type has no ToUpper()
method
No.
The equivalent of auto
in C# is var
- the compiler will deduce the appropriate type. dynamic
is determined at runtime, so it will never throw compile errors. From MSDN:
"At compile time, an element that is typed as dynamic is assumed to support any operation."
It will however throw errors at runtime if the code is invalid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With