What is difference between var and object in C#? [Resolved]

Posted by Kumarkrishna184 under C# on 12/25/2015 | Points: 10 | Views : 5385 | Status : [Member] | Replies : 9
What is difference between var and object in C#?

Thanks and Regards,
Krishna Kumar



Responses

Posted by: Sheonarayan on: 12/25/2015 [Administrator] HonoraryPlatinum | Points: 50

Up
2
Down

Resolved
Hi Kumarkrishna184,

Below are the differences between Var and Object keyword in C#

Var keyword in C#


- Introduced in C# 3 version
- Can store any type of value however the variable must be initialized while declaring
- Based on value, the data type of field is inferred
- Compiler knows what type of data is stored
- It can not be passed as method parameter.
- Useful to assign value when we are calling a method very useful when calling third party method) where we do not know what type of data the method will return

Object keyword in C#

- It can store any type of data
- All data type inherits object type
- Compiler hardly knows the data type
- It can be passed as method parameter
- To perform any operation on this, we need to unbox to it's value original data type

Hope this helps.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 12/25/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
2
Down

Resolved
@Kumarkrishna184 Sir,

(A) Among the other differences, the most catching and cardinal difference is that the datatype of var is infer by the compiler at the time of assignment .

e.g. 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.

e.g.

var unAssignedValue;

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

Another example where we cannot use var is : function return type or formal argument type

e.g


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.

object x = 1 ;// the datatype of x is object

object str = "hello DNF"; // the datatype of str is object

private object SomeFunction(object x, int y){

//do something
}


function return type is object.

Henceforth, object is use both as compile time and runtime.

(B) Point (A) also states that, since the variable type can be infered at the time of assignment, hence in case of var no overhead will be perform for extra TypeCasting (boxing, unboxing) and opposed to object where there is a high need for boxing/unboxing.

e.g.

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
}


(C) Point (A) also indicates that var is implicitly typed e.g.

var i = 10; //implicitly typed

but object is explicitly typed e.g.

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.

(D)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 = "test"; //error: Cannot implicitly convert type 'string' to 'int'

but can be done for object

object x = 1;//x is of type System.Object
x = "test"; //x is still of type System.Object

(E) Another useful use of var is that , if we are unsure about the return type and let the compiler infer that.

e.g.

var x = dbContext.EmployeeRecords(); // type is IQuerable

var x = (from x in "a,b,c,d".split(",")
select x); //type is IEnumerable

(F) 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.

(G) We cannot get the properties of anonymous Type directly using object. (Please read Solution3 of this article of us [ http://www.dotnetfunda.com/articles/show/2269/return-an-anonymous-collection-from-a-method-using-expando-object ] )

Also please read this article of us ( http://www.dotnetfunda.com/articles/show/3203/difference-between-var-and-object ) for more explanation.

Hope this helps.

Thanks



--
Thanks & Regards,
RNA Team

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 12/25/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
@Sheonarayan Sir, I was typing when you posted (:

--
Thanks & Regards,
RNA Team

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheonarayan on: 12/25/2015 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
@Rajnilari2015,

Thanks, your practical explanations are much clearer and easier to understand. Voted up!

Keep it up dear.

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 12/25/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
@Sheo Sir, thanks a lot

--
Thanks & Regards,
RNA Team

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Kumarkrishna184 on: 12/26/2015 [Member] Starter | Points: 25

Up
0
Down
Thanks to duo sir......

Thanks and Regards,
Krishna Kumar

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 12/26/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
@Kumarkrishna184 Sir, glad that the answers presented here has helped you.

--
Thanks & Regards,
RNA Team

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Amatya on: 2/16/2016 [Member] Silver | Points: 25

Up
0
Down
So clearly explained by @Rajnilari2015.. Great effort :)

Feel free to share informations.
mail Id ' adityagupta200@gmail.com
Thanks

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 2/16/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
@Amatya Sir, thanks

--
Thanks & Regards,
RNA Team

Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response