I would like to ask what is “var” in this statement.
var context = new MHC_CoopEntities();
var lists = (from c in context.InventLists
select new
{
c.InventID,
c.ItemName,
c.InventCategory.CategoryID,
c.UnitQty,
c.UnitPrice
}).ToList();
ListGridView.DataSource = lists;
ListGridView.DataBind();
I know that “var” can be any value. I am trying to create a helper class for this.
varhas nothing to do with Entity Framework. It’s a pure C# construct allowing you to define an implicitly typed object. It’s explained in the documentation. Basically it allows the compiler to infer the actual type of the variable from the right handside of the assignment. This avoids you repeating the same type declaration twice. It is also necessary for anonymous types which do not have a name. For example:And this is exactly what happens in your example. In the select clause you are returning an anonymous type. So the only way is to use
var.In the first example:
it is equivalent to:
because we know the type.