Can't loop through List-Collection of common programming errors
.png)
msdn Here’s the code:ProductList products = xxx.GetCarProducts(productCount);
List imageList = new List();
foreach(Product p in products)
{ string imageTag = HttpUtility.HtmlEncode(string.Format(@”
“, ImageUrl(p.Image, false))); imageList.Add(new CarImageList{ImageTag = imageTag}); i++; }
Under the covers ProductList is really defined like this:
public class ProductList : List
{ static Random rand = new Random(); public ProductList Shuffle() { ProductList list = new ProductList(); list.AddRange(this); for (int i = 0; i < list.Count; i++) { int r = rand.Next(list.Count – 1); Product swap = list[i]; list[i] = list[r]; list[r] = swap; } return list; } public Product FindById(int id) { foreach (Product p in this) if (p.Id == id) return p; return null; } public Product GetRandom() { int r = rand.Next(this.Count – 1); return this[r]; } } so why do I get the error when I try to foreach through the ProductList instance? Cannot convert type ‘xxx.Product’ to ‘Product’ is the error I get. But if ProductList is really List why in the world would it have an issue with conversion? C# Web Developer
-
5 Answers
.png)
msdn1 Hi NoEgo… maybe I’m missing something, but the only reason I could think of is that you have define a Product class twice. Right click and Go to Definition to see if both Product classes are the same. Other than that… on what line exatcly do you get the error? Can you post the GetCarProducts method? Regards,Fernando.
.png)
msdn2I know when I moused over Product I saw that it was the right namespace. But for some reason I still had to preface it with the namespace and walla, it’s resolved. Weird.
.png)
msdn3 Thanks. The product class is the same wherever referenced, stemming only from one Product.cs public ProductList GetCarProducts(string productCount) { … }.png)
msdn4I know when I moused over Product I saw that it was the right namespace. But for some reason I still had to preface it with the namespace and walla, it’s resolved. Weird.
.png)
msdn5Are you by any chance loading Assemblies dynamically at runtime?