Many folks have
expressed misunderstanding around the difference between var and dynamic in
C#. For both of them, the type is inferred rather than explicitly
declared.
dynamic test = 1;
var test2 = 2;
If I hover my mouse
over the “var” in the code above, IntelliSense will show me
that the compiler has correctly inferred that it is an Int32. If I hover
over “dynamic”, it will continue to be typed as “dynamic” since dynamic types aren’t resolved until runtime.
However, var is statically typed, and dynamic is not.
// Can a dynamic change
type?
dynamic test = 1;
test = "i'm a string now"; //
compiles and runs just fine
var test2 = 2;
test2 = "i'm a string now";
// will give compile error
This is one of the key
differences between dynamic and var. A var is an implicitly typed variable that is inferred by the
compiler, but it is just as strongly typed as if you had explicitly typed it
yourself using “int test2 = 2;”. A dynamic variable bypasses all compile-time type checking and resolves
everything at runtime, which generates the following scenario.
dynamic test = "i'm a string
now";
Console.WriteLine(test.Alpha); //
Won’t prompt any error as property will be checked at
runtime, resulting in exception
Other big difference between dynamic and var keyword, “dynamic” can be set as function return type while “var” cannot.
public dynamic dfunc()// Will be compiled successfully
{
return "";
}
public var func()//Compile
time error
{
return "";
}
No comments:
Post a Comment