Brian Martin
Brian Martin

Reputation: 3

Class placing a instance of its self in static list located in the class

Is this a common way to store instances in a list that can be accessed by any class. Are there any better Techniques to achieving this?

class fish
{

string species = "Gold Fish";

int age = 1;

public static list<fish> Listholder = new list<fish>();

Listholder.add(this);

}

Upvotes: 0

Views: 1601

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460128

List<T> is not thread safe, so if you want to add/remove fishs from different threads you should use ConcurrentBag<T> instead.

For example:

public class Fish
{
    public string Species { get; set; }
    public int Age { get; set; }

    private static System.Collections.Concurrent.ConcurrentBag<Fish> Aquarium = new System.Collections.Concurrent.ConcurrentBag<Fish>();

    static Fish()
    {
        var goldFish = new Fish { Age = 1, Species = "Gold Fish" };
        PutFishIntoAquarium(goldFish);
    }

    public static void PutFishIntoAquarium(Fish fish)
    {
        Aquarium.Add(fish);
    }

    public static void ClearAquarium()
    {
        Fish someFish;
        while (!Aquarium.IsEmpty)
        {
            TryTakeFishOutOfAquarium(out someFish);
        }
    }

    public static bool TryTakeFishOutOfAquarium(out Fish fish)
    {
        if (Aquarium.TryTake(out fish))
            return true;
        return false;
    }

    public static bool TryLookAtSomeFish(out Fish fish)
    {
        if (Aquarium.TryPeek(out fish))
            return true;
        return false;
    }

}

Upvotes: 3

Malachi
Malachi

Reputation: 3221

a Class has Properties.

the class allows you to create objects.

class fish()
{
    Private String _Type;
    Private Int _Age;
    Private String _Species;

    Public Type
    {
        get _Type;
        set _Type = Value;
    }
    Public Age
    {
        get _Age;
        set _Age = Value;
    }
    Public Species
    {
        get _Species;
        set _Species = Value;
    }
    public new(string Type, Int Age, String Species)
    {
        this.Type = Type;
        this.Age = Age;
        this.Species = Species;
    }
}

//this is your new object.
Fish SunFish = New Fish("small", 9, "Sunfish");

after creating an object you can create a list of objects

Upvotes: -1

Slugart
Slugart

Reputation: 4680

I think what you're trying to get at is a way to store a globally accessible list of fish somewhere. I.e. to have a central repository of fish that all other classes get their fish from.

If this is so, there are other ways of doing this such as the Service/Repository pattern. Keep in mind that having a mutable public static field will make testing and re-usability harder.

Upvotes: 0

Related Questions