Search code examples
c#objectgenericsscopegeneric-collections

The lists become empty when referenced from another class, where am i doing it wrong?


I have a class movie, where I have auto-implemented List 'Shows' to add Show class objects. I am able to add and access it in the main method, but when I call the list from another class named Access, it gives me an empty list.

I instantiated Movie class in Access class but it is creating new list instead of getting the already existing list.

I need to have a non-parameterized constructor in Movie class. I also need to be able to access the same List 'Shows' in other classes also.

// The Movie class where i create the list and store all show class objects

public class Movie
{
        public List<Show> Shows { get; set; }

        public Movie()
        {
            this.Shows = new List<Show>();
        }

        public static void Main(string[] args)
        {

            // create new object of Show type
            Show s = new Show(153, 258, 391);

            Movie mv = new Movie();

            // add object to List
            mv.Shows.Add(s);

            // The output gives me 153, which is correct
            Console.WriteLine(mv.Shows.ElementAt(0).ShowID);
        }
    }

    public class Show
    {
        public int ShowID { get; set; }
        public int MovieID { get; set; }
        public int TheatreID { get; set; }

        public Show(int showid, int movieid, int theatreid)
        {
                this.ShowID = showid;
                this.MovieID = movieid;
                this.TheatreID = theatreid;
        }
    }

   // i need to Access the list in this class
   public class Access
   {
       Movie mov = new Moive();

       // the output is showing null value error
       Console.WriteLine(mov.Shows.ElementAt(0).ShowID);
   }

I need to get be able to get and set the List from other classes in the same namespace


Solution

  • The problem seems logical since you instantiate your show list (Shows) in the constructor, each time you instantiate Movie a new show list (Shows) will be instantiated.

    In your case you must use singleton pattern

    The singleton pattern is a Creational design pattern, which guarantees a single instance of an object.

    private static List<Show> shows;
    
    public static List<Show> Shows
    {
        get
        {
            if (shows == null)
            {
                shows = new List<Show>();
            }
            return shows;
        }
     }