简体   繁体   中英

what is programming meaning of that expression in ASP.net?

what is programming meaning of that expression in ASP.net?

List<int> productsInCart = (List<int>)Session["cart"];

thanks in advance..

This is not an ASP.NET syntax, but C# one.

Session looks to be an associative array whose index is of type string . ["cart"] is indexing, ie accessing array element by it's index or "address", which here is of type string . May be you know better a term "key-value storage", not an "associative array". The terms mean the same.

Although index type is well defined for Session, it's content type looks to be defined as object , ie a type, which can hold object of any type.

List<int> productsInCart is a definition of variable of name productsInCart and of type List<int> . This type means variable contains a list (ie non-fixed length array) of integer values. Probably these values are ids of goods.

(List<int>) is type cast which in C# means just a check, that an object which was retrived from Session array, is actually of type List<int> .

In C# any subtype can be assigned to supertype variable without check. For example, List<int> variable can be assigned to object . This is always possible and requires no casting. Reverse assignment is not alway possible. Only those onject s can be assigned to List<int> variable, who actually have this type. So explicit type cast is required wich will serve as an exception source if type will be incorrect.

This expression is creating a list of type int, from existing list object which is in Session with key cart that is type cast to list<int> before assignment.

  • Session["cart"] Session is a collection that holds object, Session["cart"] hold object with key name cart.

  • (List<int>) is used to type cast the object in returned by Session["cart"]

  • List<int> productsInCart created object of type List<int>

The code

  (List<int>)

is type-casting. That means it is converting

  Session["cart"]

into the list of integer type and saving that list in the productInCart list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM