Wednesday 18 June 2014

example of var ,dynamic and object


var
Introduced in C# 3.0 
Need to initialize at the time of declaration.
e.g., var str=”I am a string”;
var cannot be used to declare variables at class level.
type safe 
in a function you can pass var as parmeter but return as object
It require type casting

dynamic

Introduced in C# 4.0
No need to initialize at the time of declaration.
e.g., dynamic str; 
dynamic can be used to declare variables at class level.
class aa 

dynamic d; //correct 


type safe
in a function you can pass dynamic as parmeter but return alos dynamic
It does not require type casting
it is use on DCOM
Object.jpg

Let's perform a mathematical operation on it.

Object1.jpg

Why are we unable to perform a mathematical operation on it and instead get an error message but in the previous example we get the type of Amount as System.Int32. If the amount is a Systme.Int32 type and we can store an integer value in it then why are we unable to apply a simple mathematical operation?

Here is the reason. Actually, an object requires explicit type conversion before it can be used. We can store anything in the object type variable but for performing an operation we must type cast it. Because C# is a statically typed language so it will throw an exception when we start performing any operation on it without proper type casting. 

Object2.jpg

Var

The var type was introduced in C# 3.0. It is used for implicitly typed local variables and for anonymous types. The var keyword is generally used with LINQ. 

When we declare a variable as a var type, the variable's type is inferred from the initialization string at compile time. 

Object3.jpg

We cannot change the type of these variables at runtime. If the compiler can't infer the type, it produces a compilation error.

Object4.jpg

Dynamic

The dynamic type was introduced in C# 4.0. The dynamic type uses System.Object indirectly but it does not require explicit type casting for any operation at runtime, because it identifies the types at runtime only.

Object5.jpg

No comments:

Post a Comment