List not getting initialized c#

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();
    }
    }
}
Jon Skeet
people
quotationmark

You've got several variables all called allProducts:

  • The static variable
  • The parameter in InitialiseMyProducts
  • The local variable in 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:

  • Remove the static variable entirely, and make InitialiseProductList return a List<Product>
  • Return all the declarations apart from the one for the static variable; InitialiseProductList should have no parameters

The 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.

people

See more on this question at Stackoverflow