Introduction
In this article i will explain about var and dynamic keyword, their difference and use.
Description
Programming languages can normally be considered to be either statically typed or dynamically typed. Its not about the Static keyword its about the compilation of Program. Programming Languages validate or check the syntax of a program either at compile time or Run-Time. Compile- Time called static Type checking and Run-Time is Dynamic Type Checking.
For example, C# and Java are a static type and JavaScript is a dynamically typed language.
C# was previously considered to be a statically typed language, since all the code written was validated at the compile time itself. But, with the introduction of the dynamic keyword in C# 4.0, it became a dynamic typed language also.
Var
The keyword 'var' was introduced in C# 3.0 (.NET 3.5 with Visual Studio 2008) .It can store any type of value but It is mandatory to initialize var types at the time of declaration.It is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time.Var type cannot be passed as method argument and method cannot return object type.
No need to cast because compiler has all information to perform operations. it is Useful when we don’t know actual type.
Dynamic-
It can store any type of the variables.Compiler didn't know about the type of data at compile Time by which it is not a type-Safe.Dynamic type can be passed as method argument and method also can return dynamic type.
Example:-
// 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
0 comments:
Post a Comment