91

Why doesn't C# have local static variables like C? I miss that!!

John Saunders
  • 160,644
  • 26
  • 247
  • 397
JoelFan
  • 37,465
  • 35
  • 132
  • 205
  • 5
    You'd have to ask the designers. – John Saunders Jun 26 '09 at 15:19
  • 10
    Trivia: VB.NET supports this using the [Static](http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx) keyword. – vcsjones Jan 09 '12 at 19:38
  • 4
    It's more than trivia - it seems like the language designers came to opposite conclusions. Would be interesting to know why. – Jon Jun 28 '12 at 02:35
  • Also, `static` means something different in C# and C++ - be careful about that. Your question nicely outlines how you don't actually know what C#'s `static` is, it might bite you in the ass some day :) – Luaan Jul 15 '14 at 14:39
  • 2
    I know what C# static means... my question is using static in the C sense – JoelFan Jul 15 '14 at 15:14
  • As others have said it has to do with where state should live, and for the most part i agree. But if you want a solution of how to do this, I have posted a generic class to mimic the functionality over here http://stackoverflow.com/a/17817240/2611613 – Iddillian Jul 23 '13 at 18:00
  • I realy would like to see an example of good local static variable usage. – Atomosk Mar 06 '17 at 04:09
  • 2
    @Atomosk Any place where you want the value to be the same each time the function is loaded, without having to expose it to the full class. – AustinWBryan Jun 06 '18 at 10:26
  • @AustinWBryan It's not an example. Function `strtok` from `string.h` is and it is very poorly designed function. With static you generaly lose thread safety, it's harder to write unit tests with statics, harder to reuse code which uses static variable. But I was wondering if there is any algorithm which works nicely only when it uses static variable. – Atomosk Jun 07 '18 at 02:22
  • 2
    @Atomosk Well you don't always have to use threads either. Someone said static locals tended to cause problems with threading, but in reality, its threading that tends to cause problems, yet people still use it. Fact is, it's one less tool in our tool belt. Though, there is a workaround but the syntax is cumbersome. And there probably is algorithms that do. Why not just look them up yourself instead of pointing to an isolated case and using that to justify them not being in the language? – AustinWBryan Jun 07 '18 at 02:28
  • @AustinWBryan Because there is good chances that author already found such algorithm and now asks that question, isn't that obvious? – Atomosk Jun 07 '18 at 02:32
  • This question is very old... now that methods can declare local functions, clearly embracing the idea of scoping small, and error prone things like type inference/lambdas were introduced into the language (and I'm not complaining about the new features, love them), I wonder if the answer from C# team has changed regarding why they don't want to have static locals... – Davi Dec 10 '19 at 09:40
  • To anyone who's still discovering this question and is interested enough to expand the hidden comments: MS accepts language proposals at Github, and this is the discussion: https://github.com/dotnet/csharplang/discussions/832 – Alex from Jitbit Apr 05 '22 at 19:06

13 Answers13

179

Because they screwed up, and left out a useful feature to suit themselves.

All the arguments about how you should code, and what's smart, and you should reconsider your way of life, are pompous defensive excuses.

Sure, C# is pure, and whatchamacallit-oriented. That's why they auto-generate persistent locals for lambda functions. It's all so complicated. I feel so dumb.

Loop scope static is useful and important in many cases.

Short, real answer, is you have to move local statics into class scope and live with class namespace pollution in C#. Take your complaint to city hall.

user313888
  • 1,937
  • 2
  • 11
  • 2
  • 78
    +1 agree, most answers here end with 'you can achieve this by... blah', but that falls short. I could achieve the desired behavior in many ways but thats not the point. Static local variables are exactly the same as static class variables but with less visibility, which is the desired behavior. – Adam Naylor Mar 12 '11 at 15:24
  • 5
    Actually it's possible in .NET, just not with C#. VB.NET for example supports local static variables. – Stefan Steiger Jun 04 '12 at 15:20
  • 8
    Actually, VB.NET just creates static class-level variables behind the scenes. Static method variables are not supported by the CLR. – JDB Aug 17 '12 at 18:22
  • Predictions that no code outside a particular function will ever need to access a particular static variable are often wrong. Were it not for method overloading, it might be possible for a method to add decorate its static variable declaration in such fashion as to permit other methods to refer to one of its variables as something like `methodName.variableName`, but the presence of overloading makes it much harder to cleanly identify a variable which is local to a particular method. – supercat Jun 13 '13 at 21:21
  • @JDB Well, the same thing happens in C++ :) Whatever you do, you're not going to get around the fact that you're now having an instance field associated with the given instance of the class. It's (moderately useful) compiler convenience, but not a separate functionality. Anything you can do with static local variables you can also do with instance fields (or static fields). – Luaan Jul 15 '14 at 14:37
  • 12
    Anytime you say "anything you can do ... you can also do" has to end with why don't you program a Turing Machine? Having the ability to narrow the scope of a variable separate from its lifetime is very useful, and static instance fields don't prevent other developers from tampering when they shouldn't - otherwise, why bother with public/private/etc. – NetMage Sep 04 '14 at 21:28
  • 7
    I wish I could give this answer a few thousand up votes. To me it isn't so much about tamper-proofing as it is about purpose-clarifying. For future me. Like tomorrow, or later today. It's not always that easy (it's often impossible) to name something so that everything about it is immediately obvious. Scope limiting is enormously helpful with that. Enormously. There's no good enough reason not to have scope limited statics. Yeah, sometimes you might realize you need access to it outside the function. So if/when that happens, refactor and give it a bigger name, more docs, and a larger scope. – Shavais Jan 17 '17 at 23:16
  • This answer is reiterated by the ridiculous responses to it. e.g., "Predictions that no code outside a particular function will ever need to access a particular static variable are often wrong" -- 1) such "predictions" are virtually never wrong, 2) no one is making any such prediction, and 3) if a need arises to access a function-local static, it can be moved to make it class-static. And "Whatever you do, you're not going to get around the fact that you're now having an instance field associated with the given instance of the class" -- static variables aren't tied to instances. – Jim Balter Nov 19 '18 at 23:28
43

The MSDN blog entry from 2004: Why doesn't C# support static method variables? deals with the exact question asked in the original post:

There are two reasons C# doesn't have this feature.

First, it is possible to get nearly the same effect by having a class-level static, and adding method statics would require increased complexity.

Second, method level statics are somewhat notorious for causing problems when code is called repeatedly or from multiple threads, and since the definitions are in the methods, it's harder to find the definitions.

[author: Eric Gunnerson]

(Same blog entry in the Microsoft's own archive. The Archive.org preserved the comments. Microsoft's archive didn't.)

Nick Alexeev
  • 1,688
  • 2
  • 22
  • 36
  • 30
    I understand this isn't necessarily YOUR opinion, but one could make the exact same argument for class level statics. "Multithreading is hard and bugprone" and "multiple users modifying the same exact static value in memory is more bugprone and difficult to track" is no excuse to not include a feature. Those are problems with the existing feature set that are not particularly exacerbated by this feature. They have static classes and static constructors for god's sake, which are even MORE renowned for being hard as hell to track and even harder to do unit tests with! – Gurgadurgen Jun 04 '16 at 07:15
32

State is generally part of an object or part of a type, not part of a method. (The exception being captured variables, of course.)

If you want the equivalent of a local static variable, either create an instance variable or a static variable - and consider whether the method itself should actually be part of a different type with that state.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 5
    Please note that in C++ you could use static "variables" for constant values. Since C# has only constants in math sense in effect you get very cumbersome way to work with local, computed, constants (like sqrt of 2, just an example). – greenoldman Apr 12 '10 at 08:52
  • 6
    Both those options are workarounds, since they have more visibility than just the local function. Creating a new class is the "cleaner" solution, but now you need more code to workaround a missing feature. – Jon Jun 28 '12 at 02:34
  • @Jon Sir, i could not understand the answer (the equivalent part of your answer), can you please provide some more light on it!! :) – Dinesh Jul 27 '12 at 16:17
  • 1
    @DnshPly9: I'm not really sure how to explain it better, to be honest. Which bit don't you understand? – Jon Skeet Jul 27 '12 at 16:18
  • 1
    Sir, the answer part -> "consider whether the method itself should actually be part of a different type with that state" what is this, i just cannot understand this? I hope if it could be explained a bit more elobarately :) – Dinesh Jul 27 '12 at 16:24
  • @DnshPly9: Well if the C version of the method would have logical state *only related to that method*, perhaps there ought to be a type with that state, containing an instance method which acts on that state. – Jon Skeet Jul 27 '12 at 16:27
  • @Jon, i thought hard on this and yes I also read a comment of yours on http://blogs.msdn.com/b/csharpfaq/archive/2004/05/11/why-doesn-t-c-support-static-method-variables.aspx and overall now I feel it makes more sense. Thank you. – Dinesh Jul 27 '12 at 16:42
  • 1
    Static state is not part of anything. The reason to allow declarations (including things like `using`) anywhere is to allow localization, which is a fundamental principle. The reason not to is ... arrogant pompous argumentum ad ignorantiam. – Jim Balter Mar 08 '13 at 07:54
  • 4
    @JimBalter: I still disagree. The state is inherently associated with the type (it lives while the AppDomain lives, and doesn't exist before the type is initialized, for example). I'd appreciate it if disagreement could be expressed without the ad hominem attacks, though... – Jon Skeet Mar 08 '13 at 13:15
  • 3
    Just saying, I'm in a situation where I need a static variable that will only be used in one method, and creating that variable in the class definition would result in (undesired) spaghetti code. – MasterMastic Mar 26 '13 at 10:44
  • 3
    @Ken: But my point would be that that is a design smell in itself. If the compiler supported this, it would have to hoist the variable to be an instance or static variable - so it *would* be part of the state of your class or instance anyway. If that's inappropriate for your class, then it's inappropriate however it's represented in source code. If it *is* appropriate, why do you want to conceal that state? – Jon Skeet Mar 26 '13 at 10:46
  • 1
    @JonSkeet Well, I'm not sure if it's really considered a state. It's a constant path relative to a specific file. I ended up creating a static class, so the code is pretty clear and the design is just fine, but I think it's still a shame I couldn't just type "static" and rid of the issue. – MasterMastic Mar 26 '13 at 11:14
  • @Ken: Ah, if you're not talking about mutable state, I think that's a different problem - or at least it's only *part* of what a static variable in C does. You can use `const` for local variables in C# of course, although that's not quite the same thing either... – Jon Skeet Mar 26 '13 at 11:25
  • 1
    @OOWonks It's possible to come up with a post-hoc Object Oriented rationale for *anything*. OO is just one approach. A tool that is sometimes the best choice, sometimes not - i.e. when it is used to clobber pragmatism. – sleep Dec 21 '13 at 01:31
  • 1
    It isn't logically valid to defeat a specific with a generality -- this is the same fallacy employed by William Paley's "watchmaker" argument against evolution. And your second paragraph contradicts the first. Static variables are not part of an object or a type, they're part of an assembly. This whole line of argument is a red herring ... the difference between class-level and method-level statics is solely *syntax*. And using class-level statics where method-level statics are wanted violates the principle of lexical locality. – Jim Balter Nov 19 '18 at 23:51
  • @JimBalter: I think we'll have to agree to disagree. (Although I *do* agree about the limited scope of method-level statics being a benefit.) – Jon Skeet Nov 20 '18 at 06:28
  • I'm no party to that agreement. I made 8 claims, and you agreed with 1, while giving no counterarguments to the others, but I am certain that at least one of those other 7 claims is correct. I can accept that you prefer not to take the time to carefully examine my points and determine which are valid, but "agree to disagree" is an evasion that I don't accept. Then again, the *sole reason* to want method-local statics is the limited scope, so I'll take that as a complete concession that the feature is desirable and there's no good reason for C# not to provide it. – Jim Balter Nov 20 '18 at 08:01
  • 1
    @JimBalter: Right: I'll accept that we won't agree to disagree, but I'm not going to concede that there's no good reason not to provide it. Stack Overflow comment threads are not intended for discussion like this, and I won't comment further. You can do so as much as you like of course, but you'll get no reply from me. – Jon Skeet Nov 20 '18 at 09:10
21

I'm not nearly as familiar with C as I am C#, but I believe you can accomplish everything you could with a local static, by using a class level static that is only used for one method. Obviously, this comes with some syntactic change, but I believe you can get whatever functionality you need.

Additionally, Eric Lippert answers questions like this on his blog a lot. Generally answered in this way: "I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature." Essentially his answers generally boil down to, it costs money to add any feature, and therefore, many potential features are not implemented because they have not come out on the positive side of the cost benefit analysis.

Timothy Carter
  • 15,459
  • 7
  • 44
  • 62
  • 24
    I couldn't have said it better myself. – Eric Lippert Jun 26 '09 at 16:23
  • 2
    The problem with implementing a local static with a class static is the class name space gets polluted unnecessarily. The problem of resource requirements for adding features to C# is why most languages from Microsoft (and others, cough, Sun/Oracle) are not fantastic. They unapologetically do what is "good enough" not what is good. – demented hedgehog May 27 '15 at 04:22
  • 3
    I can respect the second part to this answer. The first part is a solution, but not an excuse, though. That's the important part to see, here. As others have said, saying "you can accomplish X by doing Y" is no different than "you can simulate all features of any programming language with a turing machine." And yet we don't do that because despite being a "powerful enough tool," a language that only has the same functions as a turing machine (aside from infinite memory, of course) is that it is not productive enough. – Gurgadurgen Jun 04 '16 at 07:22
  • 2
    *I believe you can accomplish everything you could with a local static, by using a class level static that is only used for one method.* -- strawman. Everyone knows this, but it's completely irrelevant because it doesn't address *why* people want method-local statics -- lexical locality is an important principle and many linters inforce it. The second paragraph is like *virtus dormitiva* or *le meilleur des mondes possibles* -- generic handwaving that doesn't address the question. (C# has fortunately added a lot of good features since EL left the team.) – Jim Balter Nov 19 '18 at 23:41
  • 1
    Frequently, having a language feature actually reduces the amount of work that needs to be done, because it comes for free with the existing system, and not to have it requires work to actively remove it. The case of static locals in C# , which are already supported by the runtime, well understood and ubiquitous in other languages, falls perilously close to this case. – kaalus Mar 28 '21 at 23:46
3

So you want to use a static local variable in your method? Congratulations! You made another step towards becoming a real programmer.

Don't listen to all the people telling you that static locals are not "clean", that they impede "readability" and could lead to subtle and hard-to-find "bugs". Nonsense! They just say that because they are wannabe programmers! Lots of them are probably even toying around with an esoteric functional programming language during their free-time. Can you believe it? What a bunch of hipsters!

Real programmers embrace a paradigm I like to call SDD - Side effect Driven Design. Here are some of it's most important laws:

Don't be predictable! Never return the same thing from a method twice - even if it's being called with the exact same arguments!

Screw purity - let's get dirty! State, by nature, craves changing, because it is an insatiable monoid in the category of polyamorous endofunctors, i.e. it likes to be touched by as many collaborators as possible. Never miss out on an opportunity to do it the favor!

Among the tools used to code in a side effect driven manner are, of course, static local variables. However, as you noticed, C# does not support them. Why? Because over the last two decades Microsoft has been infiltrated by so called Clean Coders that favor maintainability over flexibility and control. Can you even remember the last time you have seen our beloved blue screen? Now guess whose fault is that!

But fear not! Real developers don't have to suffer from those poor design decisions. As has been mentioned before it is possible to have local variables that are kind of static with the help of lambdas.

However, the provided solution wasn't quite satisfactory. Using the previous answer our almost-SDD-compliant code would look something like this:

var inc = Increment();
var zero = inc();
var one = inc();

or

var zero = Increment()();

But that's just silly. Even a wannabe developer can see that Increment() is not a normal method and will get suspicious. A real programmer, on the other hand, can make it even more SDD-like. He or she knows that we can make a property or field look like a method by giving it the type Func<T>! We just have to initialize it by executing a lambda that in turn initializes the counter and returns another lambda incrementing the captured counter!

Here it is in proper SDD code:

public Func<int> Increment = new Func<Func<int>>(() =>
{
    var num = 0;
    return () => num++;
}).Invoke();

(You think the above kinda looks like an IIFE? Yes, you are right and you should be ashamed of yourself.)

Now every time you call Increment() it will return something different:

var zero = Increment();
var one = Increment();

Of course you also can make it so that the counter survives the lifetime of your instance.

That'll show them wannabe programmers!

Community
  • 1
  • 1
Good Night Nerd Pride
  • 8,245
  • 4
  • 49
  • 65
  • 7
    Is this supposed to be a serious answer to this question? It feels more like an ancient question that was taken and used as a platform to rant about "other people's" poor programming habits. – Claies Jul 07 '16 at 07:50
  • 1
    @Claies, of course, it's serious! It's the only answer showing how to properly emulate static local variables, so from the outside one almost can't tell the difference between a regular C# method and a C# "method" that manages static locals. – Good Night Nerd Pride Jul 07 '16 at 08:03
  • 1
    This is hil*arious*! I never thought about disguising a property like a method like that... Probably because this is one of the few few few cases when you'd even want that – AustinWBryan Jun 06 '18 at 10:37
  • 1
    @GoodNightNerdPride I've tried your solution and I really like it. Unfortunately it doesn't work for reference types (like `List<>`, etc, which I initialize to `null`). Is there any way one can make it work? The `Func` always returns `null`, even if I alter the returned list in methods that call the `Func`. I thought that the reference would 'stick', so to say. – silkfire Sep 20 '18 at 14:42
  • 1
    @silkfire So you want to meddle with a "static local variable" from the outside? That's the SSD spirit! But joking aside: C# reference types are references to objects, not references to references! What you are basically trying to do is this: https://dotnetfiddle.net/wd73MS Notice how the second print still shows the old count, because the list reference cannot be redirected to a new list from the outside. However, you can mutate the list by calling `Add()`, `Remove()` etc. on it. – Good Night Nerd Pride Sep 20 '18 at 15:33
  • @GoodNightNerdPride That example of yours actually works if one uses the `ref`keyword. But AFAIK lambdas have limited support for this. Investigating... – silkfire Sep 21 '18 at 08:19
  • @GoodNightNerdPride I've solved it by using a nifty `Func<,>` technique! This is so cool :) When supplying a non-`null` variable, it stores it. When supplying `null`, it retrieves it! – silkfire Sep 22 '18 at 18:09
  • @silkfire, sounds interesting. Can you show an example? Maybe with https://dotnetfiddle.net/VGO9t8 – Good Night Nerd Pride Sep 22 '18 at 19:54
  • @GoodNightNerdPride Forked your fiddle: https://dotnetfiddle.net/eEXkSi – silkfire Sep 24 '18 at 06:52
  • Static local variables are not only for modifiable state. Something I run into a lot is something like this: `GetFooByID(int id)` which returns a `Foo` object by looking it up in a static array or dictionary which is initialized once and never modified. Having the array/dictionary at method-level makes more sense than class-level. – Mr Anderson May 08 '19 at 21:18
2

C# is a component-oriented language and doesn't have the concept of variables outside the scope of a class or local method. Variables within a method cannot be declared static either, as you may be accustomed to doing in C. However, you can always use a class static variable as a substitute.

As a general practice, there are usually ways to solve programming problems in C# without resorting to using method-level statics. State is generally something you should design into classes and types, not methods.

LBushkin
  • 129,300
  • 32
  • 216
  • 265
1

Logically, yes. It would be the same as a class-level static member that was only used in that one method. However, a method-level static member would be more encapsulated. If the data stored in a member is only meant to be used by a single method, it should only be accessible by that single method.

However, you CAN achieve almost exactly the same effect in C# by creating a nested class.

Newell
  • 11
  • 1
  • Nested class has access to the private variables of the nesting class. Then you can make the variable private and put your one method in there, but you'd still have to send it the instance of the nesting class. Of course, you could make it a class extension. Then no one would be the wiser. – Lee Louviere Sep 06 '12 at 14:07
0

Because static local variables are tied to the method, and the method is shared amongst all instances.

I've had to correct myself and other programmers who expect it to be unique per class instance using the method.

However, if you make it a static class, or static instance of a class, it's syntactically clear whether there's an instance per container-class, or one instance at all.

If you don't use these, it becomes easier to refactor later as well.

Lee Louviere
  • 5,162
  • 30
  • 54
  • 1
    I think the word "static" itself should make it clear that there is only 1 variable – JoelFan Aug 30 '12 at 15:45
  • In the very few cases you need to store a 1-only variable inside a method, you must be asking yourself why you've scattered shared-class-state information through a bunch of methods. – Lee Louviere Sep 06 '12 at 14:13
  • 1
    Lee: Usually because you're dealing with re-entrance or some other similar method-specific issue. In those cases, it logically makes more sense to associate the state with the method than with the entire class, even if there's no under-the-hood difference in the way it's implemented by the CLR versus a normal private static variable. – reirab Mar 21 '13 at 16:46
0

I think the idea of local statics is just as easily solved by creating public static fields to the class. Very little logical change don't you think?

If you think it would be a big logical change, I'd be interested to hear how.

class MyClass
{
    public static float MaxDepthInches = 3;

    private void PickNose()
    {
        if (CurrentFingerDepth < MyClass.MaxDepthInches)
        {
            CurrentFingerDepth++;
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mike
  • 25
  • 1
  • 7
    Here are two big logical changes: 1) It's public and can, therefore, be modified by code outside the class. This means that other people using your class can modify it in ways unpredictable to your code. Needless to say, this is usually bad. 2) The scope for the variable is the entire class and not just the one method. Changing the scope from the one method to the entire class is a pretty big change, even if you do declare it as private. – reirab Mar 21 '13 at 16:42
0

You can use nested-class as a workaround for this. Since C# is limiting the scope of static variables to classes, you can use nested-class as a scope.

For example:

public class Foo {
    public int Increment() {
        return IncrementInternal.Increment();
    }
    
    private static class IncrementInternal {
        private static int counter = 0;
        public static int Increment() {
            return counter++;
        }
    }
}

Here Foo supports Increment method, but its support it by the private nested class IncrementInternal which contains the static variable as a member. And of course, counter is not visible in the context (other methods) of Foo.

BTW, if you want to access to Foo context (other members and methods) inside IncrementInternal.Increment, you can pass this as a parameter to IncrementInternal.Increment when you call it from Foo.

To keep the scope as small as possible, my suggestion is to create a nested class per each such method. And because it is probably not so common, the number of nested classes will stay small enough to maintains it.

I think it is cleaner than anonymous functions or IIFE.

You can see a live demo here.

nrofis
  • 8,975
  • 14
  • 58
  • 113
-2

I don't see much added benefit to local statics, if you are keeping your classes single purpose and small, there is little problem with global static pollution as the naysayers like to complain about. But here is just one other alternative.

 using System;
 using System.Collections;

public class Program
{
    delegate bool DoWork();

   public static void Main()
   {
       DoWork work = Foo().GetEnumerator().MoveNext;

        work();
        work();
        work();         
   }

    public static IEnumerable Foo()
    {
        int static_x = 10;
        /*
       do some other static stuff....
        */

      main:

      //repetative housework
      Console.WriteLine(static_x);
      static_x++;


      yield return true;
      goto main;
  }


 }
Rex Henderson
  • 412
  • 2
  • 7
-5

If you can imagine some sort of Lippert/Farnsworth hybrid entity announcing GOOD NEWS EVERYONE!, C# 6.0 allows the using static statement. This effectively allows you to import static class methods (and, it seems, properties and members as well) into the global scope.

In short, you can do something like this:

using NUnit.Framework;
using static Fizz.Buzz;

class Program
{
    [Test]
    public void Main()
    {
        Method();
        int z = Z;
        object y = Y;
        Y = new object();
    }
}


namespace Fizz
{
    class Buzz
    {
        public static void Method()
        {
        }

        public static int Z;

        public static object Y { get; set; }
    }
}   

While this is only available in C# 6.0, from what I understand the generated assemblies should be compatible with previous .NET platforms (correct me if I'm wrong).

fostandy
  • 4,282
  • 4
  • 37
  • 41
-6

You can simulate it using a delegate... Here is my sample code:

public Func<int> Increment()
{
    int num = 0;
    return new Func<int>(() =>
    {
        return num++;
    });
}

You can call it like this:

 Func<int> inc = Increment();
 inc();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    Another answer was posted a year and a half ago with this same general approach. – Servy Jul 15 '14 at 14:49
  • 9
    Very JavaScriptish – JoelFan Jul 15 '14 at 15:14
  • 6
    This doesn't solve anything. Each time you call the method, you get a new `Increment` function, with `num = 0`. If you change the `Increment` method to static, why not just use `private static num = 0;` ? You gain nothing by this. – Rob Aug 20 '15 at 05:11
  • 1
    Accepted answer has score -3. WTH? – cp.engr Jan 13 '17 at 20:29
  • 1
    No this answer does make some sense actually except it should be static. Why not add a private static you say, but that is really the question at hand, why are there no local statics. Obviously the answer is just what you suggest, why not use a class local static instead? Now we are at the real question which is class static vs local static which is better, well the context required for the local static is not a super simple one. – RJ Thompson Apr 04 '18 at 15:32
  • +1: this is exactly what i was looking for - especially useful in Code generation. Don't get why voted down. – Daniel Bişar Jan 29 '21 at 14:38