0

Hi i'm new in C# development, I want to store a List of objects in memory when I start a simple service in dotnet core with some dummy data and can be able to access them in the Controller.

List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 },
new Cat(){ Name = "Whiskers", Age=2 },
new Cat(){ Name = "Sasha", Age=14 }
};
McGuireV10
  • 9,572
  • 5
  • 48
  • 64

1 Answers1

3

A static class with a static variable will do what you want. Something like this

public static class MemoryCache
{
    public static List<Cat> Cats = new List<Cat>
    {
        new Cat() {Name = "Sylvester", Age = 8},
        new Cat() {Name = "Whiskers", Age = 2},
        new Cat() {Name = "Sasha", Age = 14}
    };
}

You can then access it from wherever you need it using something like this

Console.WriteLine(MemoryCache.Cats.Count);
Hans Kilian
  • 18,948
  • 1
  • 26
  • 35