2

I found this piece of code in a scaffolded view in a C# project, but I don't really understand the syntax after the "List" part. Why do you declare a list of prices before writing ViewBag.data? Because the ViewBag.Data already contains a query with prices converted to a list so I don't understand why that happens

@foreach (var x in ((List<WebCashRegister.Models.BLModels.Price>)ViewBag.data).Where(x => x.ProductId == item.Id).OrderByDescending(x => x.StartDate).Take(1))

that's the complete query, but my question is only about this part:

List<WebCashRegister.Models.BLModels.Price>)ViewBag.data

how does this syntax work? Thanks!

haim770
  • 48,394
  • 7
  • 105
  • 133
Markinson
  • 2,077
  • 4
  • 28
  • 56

2 Answers2

5

This tells the compiler that ViewBag.data, which can be anything since you can put anything you want in a ViewBag, is of type List<WebCashRegister.Models.BLModels.Price>.

This is an example of an explicit cast:

List<object> myList = new List<object>();
MyAunt terry = new MyAunt();
myList.Add(terry);

Now if you have a function

public void Congratulate(MyAunt somebody)

then you cannot just call

Congratulate(myList[0]);

because the compiler doesn't know that it is the right type. So you have to help the compiler by saying

Congratulate((MyAunt) myList[0]);
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
  • Your answer should at least mention "type cast"... coercion is an implicit conversion (cast), question refer to an explicit type cast... See http://stackoverflow.com/questions/8857763/what-is-the-difference-between-casting-and-coercing – Dan Feb 17 '15 at 10:32
  • In your opinion, sure. I'm just trying to be as helpful as I can. Thankfully there are God characters here with ginormous Stack Overflow scores such as you to set me straight again. – Roy Dictus Feb 17 '15 at 11:03
  • 1
    Either way @dna2 it didn't deserve a down vote, that is just petty. – user692942 Feb 17 '15 at 12:07
  • If it's all about points, you can be relieved, I've removed the downvote :) If it's just because I've a lower score than yours, I'm sorry I've dare to correct you. For me to remember: http://michael.richter.name/blogs/why-i-no-longer-contribute-to-stackoverflow – Dan Feb 17 '15 at 12:44
  • That's not what that was about, in case you didn't realize that by now. – Roy Dictus Feb 17 '15 at 13:55
  • Really interesting article, BTW. Michael Richter makes some very good points. – Roy Dictus Feb 17 '15 at 13:57
  • 1
    Thanks for all the answers, especially yours Roy! It all makes sense now, and as the others said I looked up type casting which was helpful indeed. – Markinson Feb 18 '15 at 12:13
1

Because ViewBag is defined as dynamic. Once there's a need to treat it as a List<Price> in order to perform some LINQ operations, you have to explicitly cast it to the appropriate (original) type.

See ViewBag and dynamic

haim770
  • 48,394
  • 7
  • 105
  • 133