Search code examples
c#arraysstatic-classes

Referencing a static class from an array?


I have a list of numbers, and each number that is the same should act exactly the same. So I have static classes for each number so that if I change the class, so do all of the numbers it references to.

The way the numbers are accessed is via a wrapper function, so that I'm not referencing the array directly, e.g.:

Map.GetBlock(x,y).AccessToStaticClassMembers;

So, how would I go about this?


Solution

  • I'm not really sure what you want. But it sounds like you're trying to ensure that there is only one instance in memory for each number. If that's the case, what's wrong with something like this:

    static public class ObjectMapping
    {
        static Dictionary<int, object> dictionary = new Dictionary<int, object>();
    
        static public object GetObjectForNumber(int x)
        {
            object o;
            if (!dictionary.ContainsKey(x))
            {
                o = CreateObjectForNumberTheFirstTime(x);
                dictionary.Add(x, o);
                return o;
            }
            return dictionary[x];
        }
    }
    

    Of course, I left out things such as thread safety and creation of the objects in the first access, for you to do on your own.