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.
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.
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 .
var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With