For the following code below, the foreach loop in the main() method is not displaying any values. i.e. my list is not getting initialized for display. Please help me. Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
public static List<Product> allProducts;
public static void InitialiseMyProducts(List<Product> allProducts)
{
allProducts = new List<Product>
{
new Product(){Id=1,Name="TV"},
new Product(){Id=2,Name="Bat"},
new Product(){Id=3,Name="Ball"},
new Product(){Id=4,Name="Chair"},
};
}
public static void Main(string[] args)
{
List<Product> allProducts = new List<Product>();
allProducts = new List<Product>();
InitialiseProductList(allProducts);
foreach (Product res in allProducts)
{
Console.WriteLine("ID:" + " " + res.Id + " " + "Name:" + " " + res.Name);
}
Console.ReadKey();
}
}
}
You've got several variables all called allProducts
:
InitialiseMyProducts
Main
You're initializing the local variable in Main
twice, then passing it to InitialiseMyProducts
(or InitialiseProductList
- you've changed the name half way through). However, the method then ignores the previous value and changes the parameter to refer to another list. That's irrelevant to Main
, because the argument has been passed by value.
I would suggest one of two separate options:
static
variable entirely, and make InitialiseProductList
return a List<Product>
InitialiseProductList
should have no parametersThe most important thing is first to understand why the existing code doesn't work though. Make sure all of the description above makes sense, and feel free to ask questions for extra explanation.
See more on this question at Stackoverflow