0

In which scenarios , to use var keyword to declare a variable is the best option?

As I learn that if you declare a variable using var keyword and assign any value into it, it will consider the datatype of the variable based on the value that you inserted. Yes obviously, memory overhead will increase in case of multiple usage. So which are the live examples scenarios in which to use variable declaration using var is the best option?

23rd Feb 2017, 1:22 PM
Rajan Trivedi
1 Answer
+ 3
actually compiler infers data type based on your input and this is done at compile time so there is no memory overhead....in other words both var number and int number are treated equally ar runtime. you can use implicit types as much as you want it just makes your code less readable. there are some scenarios in wich use of var keyword is mandatory for example in working with unknown types: var person = new { string Name = "foo", int age = 20} note person is not an instance of a previously defined class...compiler generates a class behind the scenes and since you don't know the name of that class you have to use var keyword!
23rd Feb 2017, 7:15 PM
HAL8999++;
HAL8999++; - avatar