Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var vs Object in C# [duplicate]

Tags:

c#

Possible Duplicate:
Difference between “var” and “object” in C#

I would like to know the difference between var and object.

When to use Var and when to use Object.

Pros and cons of using them.

like image 319
Sandeep Avatar asked Jul 10 '10 23:07

Sandeep


People also ask

What is the difference between VAR and object?

The object type can be passed as a method argument and method also can return object type. Var type cannot be passed as a method argument and method cannot return object type. Var type work in the scope where it defined. Dynamic type can be passed as a method argument and method also can return dynamic type.

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 does VAR means in C?

var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.


1 Answers

var is the answer when you find yourself asking, do I really have to type that long type name twice, in e.g.:

Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>> myDict = new Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>>();

Why no friend, you don't. Use var instead:

var myDict = new Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>>();

Now myDict really is a Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>>, so you can add things to it, enumerate it, etc.

If you declared it as object you couldn't do any operations with it that are provided by Dictionary, only the ones valid for all objects.

like image 179
Ben Voigt Avatar answered Nov 15 '22 20:11

Ben Voigt