Should you use var in C#?
Should you use it 100% of the time?
Do not use var when instantiating a simple type that could be boxed/unboxed into other simple types (int/float/decimal etc.)
int i = 4;
var i = 4;
var i = GetSimpleTypeResult(); // this is REALLY bad because is GetSimpleTypeResult() returns an integer, developers may ASSUME that and make code optimizations based on that. If GetSimpleTypeResult() later returns a decimal, no one will catch this. Whereas if GetSimpleTypeResult() returns an object 'MyResult' it is much more likely that changing the result type (for example to 'MySummary') will cause a compilation error that gets noticed.
For simple types where the type cannot be easily confused, it is really up to your team's preference.
string s = "my text";
var s = "my text"; // which is better? One saves 2 key strokes, but is .01% more ambiguous. (It is obviously a string, not a number, not a boolean, etc)
var bool = true;
boolean b = true;
bool isSuccess = GetResult(); // assuming this is a Boolean, this is a reasonable line of code.
var isSuccess = GetResult(); // assuming this is a Boolean, this is a reasonable line of code.
var x = GetResult(); // what is x? At least with isSuccess we could reasonably guess that it was a Boolean.
Do not use var if the variable name or method/constructor do not provide some good indication of what the object is.
var person = ComplexFunction(); // IF ComplexFunction() returns a person, this is okay
var p = GetPerson(); // IF GetPerson returns a person, this is okay
Person p = ComplexFunction();
var p = ComplexFunction(); // this is bad because we have no idea what p is
Use var for anonymous types or really long object names that no one cares about.
var query = from p in people where p.Id > 0 select p;
var itemResponseCodes = new List<ItemResponseCode> ();
var ircs = new List<ItemResponseCode> (); // variable name is okay, but could be improved
IQueryable<TblPeople> query = from p in people where p.Id > 0 select p; // readability is horrible, too long to type
List<ItemResponseCode> ircs = new List<ItemResponseCode> (); // readability is horrible, too long to type
Do use var for long object names, use descriptive variable/ method names as often as you can, never use var for numeric simple types, and always err on the side of NOT using var if there is any question of ambiguity or confusion.
Created By: amos 3/25/2015 11:29:02 AM
Updated: 11/25/2015 8:48:45 AM