Difference between Var and Object

Rajnilari2015
Posted by in C# category on for Beginner level | Points: 250 | Views : 989 red flag
Rating: 4 out of 5  
 1 vote(s)

A much asked question in an interview is the difference between Var and Object. In this article we will discuss about the same.

Introduction

A much asked question in an interview is the difference between Var and Object. In this article we will discuss about the same.

Difference between Var and Object

Below are the differences between Var and Object keywords.
(A)The cardinal difference is that the datatype of var is inferred by the compiler at the time of variable assignment.

var x = 1;

This indicates that "x" is a variable of type int or (Struct System.Int32).

 var str = "Hello DNF";

Compiler infers that "str" is of type string(System.String).

Since the data type inference happens at the time of variable initialization, henceforth, it is mandate to assign values to variables in case of var, else the compiler will report error.

var unAssignedValue;

This is a erroneous statement since from here the compiler can never infer the datatype of "unAssignedValue" variable.

However, the case is completely untrue for the case of object which derives from System.Object

object x = 1 ;// the datatype of x is object
object str = "Hello DNF"; // the datatype of str is object

(B)We cannot use var for  function return type or formal argument type

private var SomeFunction(var x, int y){

	//do something
}

Here x and y are formal arguments/parameters. Since datatype of "x" is not known to the compiler, it reports error. In a similar way, the function return type is unknown to the compiler and hence the error will be generated.

However, the case is completely untrue for the case of object which derives from System.Object

private object SomeFunction(object x, int y){

	//do something
}

function return type is object.

So from point (A) and (B),we can infer that object is use both as compile time and run time.

(C) Point (A) also states that, since the variable type can be inferred at the time of assignment, hence in case of var no overhead will be perform for extra Type Casting (boxing, unboxing) and opposed to object where there is a high need for boxing/unboxing.
private object SomeFunction(object x, int y){

	return (int)x + y; // note the type casting for the variable
}

void main(){

	int x = (int)SomeFunction(10,20); // note the type casting for the function
}

(D)Point (A) also indicates that var is implicitly typed

var i = 10; //implicitly typed 

but object is explicitly typed

object o = 10;

var i =  (int)o ;//explicitly typed

An implicitly typed variable , on the other hand is strongly typed,and the compiler determines the type.

(E) Once Var has been initialized, we can't change type stored in it.
    var x = 1;//x is of type System.Int32            
    x = x++;// valid statement
    x = "some string value"; //error: Cannot implicitly convert type 'string' to 'int'

but can be done for object

object x = 1;//x is of type System.Object
x = "some string value"; //x is still of type System.Object
(F) Another useful use of var is that , if we are unsure about the return type and let the compiler infer that.
var x = new dbContext.Employees.Where(e => e.Age > 30); // type is IQuerable

var x = (from x in "a,b,c,d".Split(",")
	 select x); //type is IEnumerable
(G) We cannot fire Linq/Lambda expression directly on objects datatype but can easily on VAR types.

Reason is that object datatype exposes only 4 methods namely -

	- Equals
	- GetHashCode
	- GetType
	- ToString

For Linq/Lambda to get applied, the object must be classified under System.Collection namespace and must be of type IList<T>, ICollection<T>,IEnumerable<T>,IQuerable<T> so that it can have the GetEnumerator() that iterates through the collection.

(H) We can access the properties of the Anonymous Type directly using var but not with objects

 //create a new anonymous type and assign to a var
var x = new
{
  Name = "RNA Team",
  Age = 4
};

We have created an anonymous type call x with two properties "Name" and "Age" and assigned some values. We can access those properties as under

 var accessAnonymousProps = $" Name : {x.Name}, Age : {x.Age}";

The same is not possible for the case of objects as under

(I) Last but not the least, var was introduced in C# 3 version and object in C# 1.0 version

Conclusion

In this article, we have discussed the various difference between var and object with many examples. Hope this will be helpful. Thanks for reading.

Recommendation
Read Post message with image on twitter using C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)