Hayden
Hayden

Reputation: 2988

Design Pattern for List of Immutable Objects usage

Lets say I have an object of type Foo, which when initialized, will be immutable. Since these objects are immutable, and I want to be able to access any of these Foo objects, I initialize and store these objects in a static class (FooHandler) which contains a list of all the Foo objects.

Currently however, if a class wants to access this object, I give them the index of where the Foo object is located in the list in FooHandler, and have a getter method to return the object itself when needed. The intent of this is to save on memory by not having two of the same objects in circulation (which I consider a waste).

Is there a better approach in C# for referencing these objects (like a pointer or something similar) or a better structure entirely for how to approach this problem, as I feel giving an index to an immutable object is too hackish and error prone?

Example code:

public class Foo {
    public int A { get; private set; }
    public int B { get; private set; }

    public Foo(int a, int b) {
        A = a;
        B = b;
    }
}

public static class FooHandler {
    private static List<Foo> fooList;

    static FooHandler() {
        fooList = new List<Foo>();

        fooList.Add(new Foo(1, 2));
        fooList.Add(new Foo(3, 4));
    }

    // Assume there is error checking
    public static Foo GetFoo(int index) {
        return fooList[index];
    }
}

public class Bar {
    public int FooID { get; private set; }

    public Bar(int fooID) {
        FooID = fooID;
    }

    public void func() {
        Console.WriteLine(FooHandler.GetFoo(FooID).A);
    }
}

Note: I know this example could be considered mutable, just wanted to type something up quickly without too much testing.

Upvotes: 2

Views: 263

Answers (1)

Guvante
Guvante

Reputation: 19203

C# already passes around reference types (denoted by class) with a reference (roughly equivalent to a pointer).

You need not do anything special to get this and it happens automatically. There is no waste in just returning the Foo directly.

Upvotes: 3

Related Questions