| var | dynamic |
|
Introduced in C# 3.0 |
Introduced in C# 4.0 |
|
Statically typed – This means the type of variable declared is decided by the compiler at compile time. |
Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time. |
|
Need to initialize at the time of declaration. e.g., Looking at the value assigned to the variable |
No need to initialize at the time of declaration. e.g.,
|
|
Errors are caught at compile time. Since the compiler knows about the type and the methods and properties of the type at the compile time itself |
Errors are caught at runtime Since the compiler comes to about the type and the methods and properties of the type at the run time. |
|
Visual Studio shows intellisense since the type of variable assigned is known to compiler. |
Intellisense is not available since the type and its related methods and properties can be known at run time only |
|
e.g., will throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value. |
e.g., will compile; |
|
e.g. will compile
|
e.g. will compile and run
will compile and run since the compiler creates the type for obj1 as System.Int32 and then recreates the type as string when the value “I am a string” was assigned to it. This code will work fine. |
var 与 dynamic的不同
最新推荐文章于 2025-05-14 17:55:24 发布
本文深入解析了C#中的静态类型和动态类型变量的区别与使用场景,包括初始化方式、编译时与运行时错误捕获、Intellisense功能以及示例代码演示。
157

被折叠的 条评论
为什么被折叠?



