Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyword "auto" C++ and "dynamic" C#

Does "dynamic" keyword in C# work like "auto" in C++

More details:

auto a = 5; //C++

dynamic a = 5; //C#

Are they similar?

like image 615
user3663338 Avatar asked May 22 '14 04:05

user3663338


2 Answers

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

like image 138
Rahul Avatar answered Oct 28 '22 14:10

Rahul


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.

like image 38
bhamlin Avatar answered Oct 28 '22 14:10

bhamlin