Back in C++ days from time to time I used static variables and it is annoying to me that in C# when I need small cache or something like this I cannot pin it to the method, but I have to pollute entire class with the implementation information — “hey, I use cache, come on and break it”. After reading the explanation why C# does not have static variables I am even more convinced you cannot really substitute it with hope and crossed fingers.
Consider how Skila does it:
class !TreeNode static var counter Int = 0; // this is a field let id Int; def init() id = counter++; end end
Well, no magic here, I want to have id
field per each object I create, so I need to have a global (per type) counter. This is C# style, every method can now interfere with the field counter
and I definitely would like to avoid it. Let’s fix it:
class !TreeNode let id Int; def init() static var counter Int = 0; // this is a field this.id = counter++; end end
The only difference is scope, and thus the visibility of the counter
field. Since no other method can see it, no other method can mess with it (which gives a little bonus — the name is taken only within the method). However what the field sees didn’t change a bit — you still cannot initialize a field with local data, exactly as before.
Oh, right, this post is about “static variables”, not “static fields” — well, you can call them “static variables” now.