Home » .Net

What is difference between object, var and dynamic keywords in C#?

Learn: What are an object, var and dynamic keywords in C#.Net? What are the differences between them?

Object

It is a type which is base of all the types and one of the oldest features of the language. It means values of any types can be stored in object type variable. But type conversion (un-boxing) is required to get original type when the value of variable is retrieved in order to use it.

Object o;
o = 10;

So it is an extra overhead of un-boxing. Thus object type should only be preferred if we have no more information about the data type.

Compiler has title information of object type.

Var

This was introduced in .net 3.5 framework. This also can have any type of values like object but it is must to initialize the value at time of declaration of the variable. The keyword is best suited for linq queries in C#.

Var a = 10;
Var b = "string value";
Var c = new Product(); //  object of product type
Var d;//Error, as the value is not assigned at time of declaration of variable d
d = 10;

Dynamic

This keyword was introduced in .net 4.0 framework. This also can be used to store any type of value like object and var but unlike object un-boxing is not required at time of using the variable.

Dynamic d1 = 10;
Dynamic d2;
D2=new Product();
Dynamic d3="string value";

Compiler has no information of dynamic type but value is evaluated at run time.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.