Q:

What is the difference between var and dynamic in C#

0

What is the difference between var and dynamic in C#

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

var keyword:

The var keyword was introduced in C# 3.0 and variables declared with var are statically typed. Here, the type of variable declared is decided at the compile time. Variables that are declared as var should be initialized at the time of declaration. By looking at the assigned value, the compiler will decide the variable type. As the compiler knows the data type of the variable at compile-time, errors will be caught at that time only. And Visual Studio 2008 and later versions will show the IntelliSense for var type.

Example,

var obj "aticleworld.com";

In the above sentence, obj will be treated as a string

obj = 20;

In the above line, the compiler will throw an error, as the compiler already decided the type of obj as String and assigned an integer value to string variable violating safety rule type.

dynamic keyword:

The dynamic keyword was introduced in C# 4.0 and variables declared with dynamic were dynamically typed. Here, the type of variable declared is decided at runtime. Variables that are declared as dynamic don’t need to initialize the time of declaration. The compiler won’t know the variable time at the time of compiling, hence errors can’t be caught by the compiler while compiling. IntelliSense is not available since the type of variable will be decided at runtime.

Example,

dynamic obj = "aticleworld";

In the above code, obj will be treated as a string.

obj = 20;

The compiler will not throw any error, though obj is assigned to the integer value. The compiler will create the type of obj as String and then it recreates the type of obj as an integer when we assign an integer value to obj.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Interview Questions and Answers,You Need To Know

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is the use of ‘using’ statement in C#?... >>
<< What is the difference between ref & out parameter...