Difference between var and dynamic?

 Posted by Ddd on 2/21/2011 | Category: C# Interview questions | Views: 22330 | Points: 40
Answer:

var:
1)It is a keyword that is used for implicit variable declaration
ex: var a=100;
var b="welcome";
The compiler determines the datatype of the variable declared with var keyword
on the basis of assigned value. we have to assign value with variable declaration
ex: var a;
a="welcome"; This is wrong


2)var cannot be used to declare variables at class level.
3)var cannot be used as the return type of methods.
4)Intoduced in c# 3.0

dynamic:
1)It is a keyword used for variable declaration

ex: dynamic a=100;

dynamic b;
b="good";

The datatype of the variable is determined at runtime

2)dynamic can also be used to declare class level variables

ex: class aa
{
dynamic d; //correct

}

3)dynamic can also be used as return type of the methods

example:

class dd
{
static dynamic pp()
{
dyanmic d;
d=<some value>;
return d;
}
}

4)Introduced in c# 4.0


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Akiii on: 3/17/2011 | Points: 10
good description......

Thanks and Regards
Akiii

Login to post response