JimmyPop13
JimmyPop13

Reputation: 317

Accessing elements of a list in another class

Lets say I have something like the following.

namespace BurgerMachine
{
public class BaseList{

    private static readonly List<Bases> bList = new List<Bases>() //might need to take off readonly
    {
        new Bases(){ BaseID=1, BaseName="Bun"},
        new Bases(){ BaseID=2, BaseName="SeededBun"}
    };
    public static List<Bases> GetList()
    {
        return bList;
    }
}
    public class Bases
    {
        public int BaseID { get; set; }
        public string BaseName { get; set; }
    }
}

Now I would like to access the elements of the above list from another class, is this doable with my current setup or do I need to be returning more?

I have seen a few examples of people creating a List and then adding to from another class but not trying to access elements that already exist. If such an example does exist please point me in the right direction.

First time using Lists in this fashion so I'm not quite sure what I am doing. Any help would be great. If more information is needed please ask.

Upvotes: 3

Views: 94

Answers (2)

Rahul
Rahul

Reputation: 77936

Well you could just make the list a public member like below and access it from wherever you want

public List<Bases> bList = new List<Bases>()
{
    new Bases(){ BaseID=1, BaseName="Bun"},
    new Bases(){ BaseID=2, BaseName="SeededBun"}
};

You can access now saying

var blist = new BaseList().bList;

With your current setup (as already commented) why can't you just call the static method saying BaseList.GetList()

Upvotes: 2

Arvind Vishwakarma
Arvind Vishwakarma

Reputation: 563

Here are few implementations best way to return list.

With static class

public class BaseListProvider
{
    public static readonly Bases Bun = new Bases() { BaseID = 1, BaseName = "Bun" };
    public static readonly Bases SeededBun = new Bases() { BaseID = 2, BaseName = "SeededBun" };

    public static IEnumerable<Bases> GetList()
    {
        return new[]
        {
            Bun,
            SeededBun
        };
    }
}

public class Bases
{
    public int BaseID { get; set; }
    public string BaseName { get; set; }
}

With interface which can be helpful if you are using dependency injection

public class BaseListProvider : IBaseListProvider
{
    public static readonly Bases Bun = new Bases() { BaseID = 1, BaseName = "Bun" };
    public static readonly Bases SeededBun = new Bases() { BaseID = 2, BaseName = "SeededBun" };

    public IEnumerable<Bases> GetList()
    {
        return new[]
        {
            Bun,
            SeededBun
        };
    }
}

public interface IBaseListProvider
{
    IEnumerable<Bases> GetList();
}

public class Bases
{
    public int BaseID { get; set; }
    public string BaseName { get; set; }
}

Upvotes: 2

Related Questions