Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "var" and "object" in C# [duplicate]

Tags:

c#

types

Is the var type an equivalent to Variant in VB? When object can accept any datatype, what is the difference between those two?

like image 459
user184805 Avatar asked Oct 12 '09 05:10

user184805


People also ask

Can var be an object?

Nope - var just means you're letting the compiler infer the type from the expression used to assign a value to the variable. So if you have an expression like: var x = new Widget(); x will be of type Widget , not object .

What is the difference between dynamic and object?

Object is useful when we don't have more information about the data type. Dynamic is useful when we need to code using reflection or dynamic languages or with the COM objects and when getting result out of the LinQ queries.

What is the difference between VAR and dynamic type?

dynamic variables can be used to create properties and return values from a function. var variables cannot be used for property or return values from a function. They can only be used as local variable in a function.

What is the difference between VAR and string?

Var is used to declare Implicitly typed variable where the compiler identifies the type automatically. var can hold any type of data. String is an explicit declaration for holding string data only.


1 Answers

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; //implicitly typed int i = 10; //explicitly typed 

var isn't object

You should definitely read this : C# 3.0 - Var Isn't Object

like image 60
Tarik Avatar answered Sep 22 '22 06:09

Tarik