Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple static variable scopes within same application?

What is the best way to set up multiple static scopes within the same application? I have structs that serve as wrappers over accessing an array.

Here's an example:

class FooClass{
   static int[] BarArray;
}

struct FooStruct{
    public int BarArrayIndex;

    public int BarArrayValue { 
      get { return FooClass.BarArray[BarArrayIndex]; } 
      set { FooClass.BarArray[BarArrayIndex] = value; }
    }
}

For performance reasons, I don't want to store a reference to BarArray in every instance of FooStruct, hence I declared the array static. However, it's possible that in the future I'll have to work with multiple different BarArrays at the same time (where different instances of the struct should point into different arrays). Is there a way to achieve that without having to store an additional reference in every instance of the structs and not using a static variable neither? If not, what's the best way to use multiple static instances while making the whole application feel as "one application" for the end-user?

like image 515
user974608 Avatar asked May 08 '26 21:05

user974608


2 Answers

You seem to think that holding a reference to an array means copying the array .. ie that each instance of your struct would contain a copy of the array? This is not the case. All the struct would contain is a reference to the array ... a pointer. There would only exist one instance of the array in memory. I'm not sure this is gaining you any performance points.

like image 117
iDevForFun Avatar answered May 11 '26 10:05

iDevForFun


You can't. The point of static is to have one instance over the whole application.

Have a look at Dependency Injection instead. It should fulfill your usecase perfectly fine and is the prefered way of handling such a problem.

like image 25
Femaref Avatar answered May 11 '26 11:05

Femaref