# Diff between var and dynamic keyword.
In C#, variables must be declared with the data type. These are called explicit typed variables.
Example: Explicitly Typed Variable
int i = 100;// explicitly typed variable
Note:- explicit means precisely and clearly expressed(here i is a variable of integer data type)
C# 3.0 introduced var keyword to declare method level variables without specifying a data type explicitly.var is called implicit typed local variable.
Example: Implicitly Typed Local Variable
var j = 100; // implicitly typed local variable
Note:- Implicitly-typed variables must be initialized at the time of declaration; otherwise C# compiler would give an error:
var i; // Compile-time error
In
C# 4.0, a new type is introduced that is known as a dynamic type. It is used to
avoid the compile-time type checking. The compiler does not check the type of
the dynamic type variable at compile time, instead of this, the compiler gets
the type at the run time. The dynamic type variable is created using dynamic
keyword.
Example:-
class Program
{
dynamic i;
static void Main(string[] args)
{
dynamic j=100;
}
}
var vs dynamic
- var is a statically typed variable. It results in a strongly typed variable, in other words the data type of these variables are inferred at compile time. This is done based on the type of value that these variables are initialized with.var type of variables are required to be initialized at the time of declaration or else they encounter the compile time error: Implicitly-typed local variables must be initialized.
- dynamic are dynamically typed variables. This means, their type is inferred at run-time and not the compile time in contrast to var type.dynamic type variables need not be initialized when declared.
Example:-
class Program
{
//Used as a Field
dynamic i;
static void Main()
{
//Implicit Type Local Variable
var a=10;
//Nullable<int> b = null;
//Local Variable
//Explicit Typed
int b=20;
//Dynamic Type
dynamic c=30;
Console.WriteLine("Value of A:" +a);
Console.WriteLine("Value of B:" + b);
Console.WriteLine("Value of B:" + c);
}
}
No comments:
Post a Comment