For some static methods I realise it is extremely convenient to use a small array to temporarily store values during an operation. Said array is useful because you need indexing, but allocating that small array everytime the method is invoked.
Is this a good way to work around the lack of C-like static locals in C#?
[ThreadStatic]private static int[] staticregister = new int[4];
public static bool CoolStaticMethod(int[] largearray)
{
//...
}
My assumption is that a method which can’t call itself, either directly (recursive) or indirectly, can only be called singularly in a single thread, thus the fake static local should be declared thread-static and the problem is largerly solved.
Edit:
I must add that the contents of the register is garbage between method invocations.
It is not what I would call a good workaround, no. It will work (assuming you are sure about the re-entrancy risks, i.e. not calling into itself, even via accidental events/callbacks/etc) – but…
In my opinion, it is stateful, make it an instance:
and simply use different instance of
WheverTheTypeIsfor each context, i.e. the instance acts as the context. Just use a different instance per thread if you want context per-thread. This also allows usage with callbacks, parallelism, workers, etc to continue in the same context. Note that there are many frameworks that do not guarantee a single thread (WCF, ASP.NET, WPF for examples), and this is only going to increase as 5.0 introduces moreasync/await-oriented code.If you are deeply tied to static methods, passing the
registerin as a second parameter would suffice too:If the issue is the allocation of a 4-byte array:
stackallocandunsafeto avoid the allocationFor an example of “2”: