I would like to ask a theoretical question. If I have, for example, the following C# code in Page_load:
cars = new carsModel.carsEntities();
var mftQuery = from mft in cars.Manufacturers
where mft.StockHeaders.Any(sh=> sh.StockCount>0)
orderby mft.CompanyName
select new {mft.CompanyID, mft.CompanyName};
// ...
Questions:
- This code uses the
varkeyword. What is the benefit of this construct? - What is the key difference between the implementation of
varin Javascript and C#?
JavaScript is a dynamically typed language, while c# is (usually) a statically typed language. As a result, comparisons like this will always be problematic. But:
JavaScript’s
varkeyword is somewhat similar to C#’sdynamickeyword. Both create a variable whose type will not be known until runtime, and whose misuse will not be discovered until runtime. This is the way JavaScript always is, but this behavior is brand new to C# 4.JavaScript has nothing to match C#’s
var, since JavaScript is a dynamically typed language, and C#’svar, despite popular misconception, creates a variable whose type is known at compile time. C#’svarserves two purposes: to declare variables whose type is a pain to write out, and to create variables that are of an anonymous type, and therefore have no type that can be written out by the developer.For an example of the first:
Anonymous type projections from Linq-to-Sql or Entity Framework are a good example of the second:
Here
resultsis of typeIQueryable<SomeTypeTheCompilerCreatedOnTheFly>. No matter how much you might like to write out the actual type of results, instead of just writingvar, there’s no way to since you have no knowledge of the type that the compiler is creating under the covers for your anonymous type—hence the terminology: this type is anonymousIn both cases the type is known at compile time, and in both cases, subsequently saying either
or
would result in a compiler error, since you’re setting
connandresultsto a type that’s not compatible with what they were declared as.