Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys ,

I found a csharp code in a book which am not able to understand can you please tell what it is IEnumerable . why its added here

C#
@foreach (Album a in (ViewBag.Albums as IEnumerable)) {
@a.Title
 }



Thanks In Advance Guys

What I have tried:

Need to know what is IEnumerable . why its used in the used in this code
Posted
Updated 17-Jul-16 4:45am
Comments
Karthik_Mahalingam 17-Jul-16 8:00am    
it refers casting the viewbag object to an ienumerable type.

this also will work.
@foreach (Album a in ViewBag.Albums ) {
@a.Title
}

It's probably there (this is a guess) because the view code doesn't know what type ViewBag.Albums is at compile time (because ViewBag is a dynamic object) so the view won't compile if you try and loop through something that can't be looped through. By putting "as IEnumerable" it is going to cast ViewBag.Albums to IEnumerable which allows the object to be looped through. This allows the view to compile, however if the controller puts something in ViewBag.Albums that can't be cast to IEnumerable you'll get a run-time error.

A better solution to these issues is to use a proper model which is strongly-typed so the view would know what type Model.Albums is at compile time.
 
Share this answer
 
IEnumerable is a generic collection of enumerated values (i.e., a list of objects). The code is casting the dynamic object ViewBag.Albums as a generic collection and then going through each enumeration by using the foreach command.
 
Share this answer
 
RTFM[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900