C# Declare a Static List

19,314

If I understand you, you want an Application wide static list.

Why not create a new file called ApplicationServices.cs and put a static class inside of it with a static List<Song>

public static class ApplicationServices{
      public static List<Song> Songs {get; set;}
}

This way you can access it everywhere by calling ApplicationServices.Songs

Share:
19,314
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am using a Static List to store some values, the idea is declare the list, then a button in page 1 adds some values, then a button in page 2 adds some more values, to do this I am triying declare it in each page but the list is newly created:

    public static List _songlist = new List(); in each page.

    Can you help me?, how I can declare the static list then have the same list with the values in all the pages?

    public static List<Song> _songlist = new List<Song>();
    
    public class Song
    {
    private string _name;
    public string name
    {
    get { return _name; }
    set { SetProperty(ref _name, value); }
    }
    private string _artist;
    public string artist
    {
    get { return _artist; }
    set { SetProperty(ref _artist, value); }
    }
    }
    

    Any help is appreciated.

    • TaW
      TaW almost 8 years
      Where is the problem? Where do you declare the _songlist ? If it is in, say mainWindow, you can access it as mainWindow._songlist..
    • jdweng
      jdweng almost 8 years
      You need to move the 'new' so it is only perform once in the code (new List()),
    • Admin
      Admin almost 8 years
      You say put only one with new and the rest with "public static List<string> _lista = List<string>();" it show error: "Non-invocable member 'List<T>' cannot be used like a method."
    • howcheng
      howcheng almost 8 years
      "Static" means only one instance. If "I am triying declare it in each page but the list is newly created" then on every page load, you just overwrote what the last page did. Page 1 creates a list and adds values to it. On Page 2, you declared a brand new list, so the list from Page 1 is now gone.
  • Admin
    Admin almost 8 years
    Thank you, I am studing your comment now.
  • DotNetRussell
    DotNetRussell almost 8 years
    @Julius if this works for you please don't forget to checkmark and upvote. Thanks