1) Introduced in C# 3.0
2) Variables declared with var are implicitly but statically typed
3) Statically typed – This means the type of variable declared is decided by the compiler at compile time.
4) Need to initialize at the time of declaration.
e.g., var str=”I am a string”;
Looking at the value assigned to the variable str, the compiler will treat the variable str as string.
5) 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
6) Visual Studio shows intellisense since the type of variable assigned is known to compiler.
7) e.g., var obj1;
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.
8) e.g. var obj1=1;
var obj1=” I am a string”;
will throw error since the compiler has already decided that the type of obj1 is System.Int32 when the value 1 was assigned to it. Now assigning a string value to it violates the type safety.
1) Introduced in C# 4.0
2) Variables declared with dynamic are dynamically typed.
This capability was added to the CLR in order to support dynamic languages like Ruby and Python.
3) Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.
4) No need to initialize at the time of declaration.
Ex: dynamic str;
str=”I am a string”; //Works fine and compiles
str=2; //Works fine and compiles
5) 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.
6) Intellisense is not available since the type and its related methods and properties can be known at run time only
7) Ex: dynamic obj1; will compile
8) Ex: dynamic obj1=1;
will compile and run
dynamic obj1=” I am a string”;
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.
Mark This Response as Answer
If this post helps you mark it as answer
Login to post response