Share via


Why doesn't C# support static method variables?

Q: In C++, it's possible to write a static method variable, and have a variable that can only be accessed from inside the method. C# doesn't provide this feature. Why?

A: 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]

Comments

  • Anonymous
    May 11, 2004

    Thank you for your explanations, but I'm not at all happy with it...

    First, there are a lot of C# features which could be done another way, but we like C# because it offers already known features more elegant.
    Second, threading as such is also 'somewhat notorious for causing problems' but that does not stop us using it. Additionally, it is not at all elegant to have class-level static variables which in fact belongs to a method. They get degraded to 'class global variables' and it's just a question of time until another developers misuse them and we will earn side effects.
    Of course, it's possible to put such a method in it's own class, but I think we don't really have to discuss such 'solutions' here.

    I'm sure, that static method variabls must be used carefully, but then, they make sense and are very useful.

    kind regards,
    Thomas
    Schittli

  • Anonymous
    May 12, 2004
    I must agree with Thomas, especially when the C# team decided to add features such as partial types - don't you those are going to make finding definitions of anything a lot harder than method static variables? I hope those three reasons posted are not the actual reasons the C# design team based their decisions on.

    As for method static variables being problematic when the method is called from multiple threads - how exactly are they different from class static members? From the implementation point of view they're class static members that are scoped to a single method.

  • Anonymous
    May 21, 2004
    I'm with the C# team on this one. A method itself doesn't logically have state outside the period during which it's being called. If you've got a method which has separate state, it should be a separate object - or the state should be part of the class.

  • Anonymous
    June 04, 2004
    I agree, I don't believe that a method should encapsulate data. That is the purpose of an object.

  • Anonymous
    July 06, 2004
    ironically vb.net supports them. Go figure.

  • Anonymous
    July 07, 2004
    It seems to me there are two angles of approach. The language designers are trying to follow a rationale that fits the principles underlying the language. Programmers are trying to do a job and know which features they find useful. The C# team have had a rare opportunity to design a language from scratch and are keen to keep it as ‘clean’ as possible. On the other hand the VB team are re-designing an existing language and, I suspect, are more likely to keep features which are arguably not ideal but serve a very useful purpose. The idea of a variable which is scoped to a method but retains its value between calls is very old and useful in certain circumstances. Enumeration is one which comes to mind. On balance, rather than write a whole class to do a single simple job, I would prefer to be able to do it in a single function.

  • Anonymous
    July 25, 2010
    The comment has been removed

  • Anonymous
    May 12, 2011
    The comment has been removed

  • Anonymous
    June 24, 2011
    C# does allow state scoped to a method in other contexts, autoproperties and events. I'd rather allow it with a warning, then the coders can set policies to control whether they want to allow it to compile or not.

  • Anonymous
    April 10, 2012
    in C# every thing is in class. It cannot have method like in c , c++ which does not belong to any class.Hence there is no point in using static class method variables. At any time we have an alternate to declare static member variable for that method i.e class A { public void fun1() { static int count =0; //oops its an error in c# } public void fun2() { static int count =0; //oops its an error in c# } } For  this  we can always have alternate like class A { static int fun1_count =0; static int fun2_count =0; public void fun1() { } public void fun2() { } }

  • Anonymous
    August 01, 2012
    yes, we can use a class level variable (private), but a method-level static is really nice for encapsulating things that are used for recursion implementation

  • Anonymous
    February 07, 2013
    The comment has been removed

  • Anonymous
    March 07, 2013
    Those aren't reasons, they are ridiculous excuses. All declarations (including 'using') should be allowed everywhere, to allow for localization of reference ... uses of the same name (or other information) should be grouped as close together as possible.

  • Anonymous
    March 07, 2013
    " A method itself doesn't logically have state outside the period during which it's being called." Utter nonsense.

  • Anonymous
    May 03, 2013
    How about this for a good use. I would really like this to not be a global variable since i have lots of registry values to read. class a{ shared bool some_value; public static bool hasEverBeenConfigured { get {   static bool readRegistry = true;   if(readRegistry)   {       readRegistry = false;       some_value = readfromregistry;   }   return some_value; } } }

  • Anonymous
    May 16, 2013
    I disagree with these "reasons" C# doesn't support static variables in methods.  Particularly the statement that "statics are somewhat notorious for causing problems when code is called repeatedly or from multiple threads"...it is precisely because of multiple threads that static variables can be useful in methods.  They can, for example, be used for throttling or to prevent re-entrancy.

  • Anonymous
    June 13, 2013
    I researched this because I was looking at some code that handled INotifyPropertyChanged with:         SetProperty(MethodBase.GetCurrentMethod(), ref _isEditMode, value); The expense of calling refelction everytime the property is updated seems to outweigh the benefit of using "IsEditMode". Consequently, it would be nice to have:            set            {                static var propertyName = MethodBase.GetCurrentMethod();                SetProperty(propertyName, ref _isEditMode, value);            } Creating and naming a class level static for each property would defeat the purpose of this construct.

  • Anonymous
    October 25, 2013
    I cannot imagine why local static variables would be bad for anything any more than static class variables. After compilation they are static class variables, BUT they don't pollute the "namespace" of the class for the programmer. They can be very elegant in a great many situations, whenever there is a value which conceptually they belong to a single method but is otherwise static. The workarounds proposed in this thread are worse than the problem they solve (class namespace pollution).

  • Anonymous
    September 04, 2014
    So I looked this up again when I came across another place for it - in ASP.Net, I want to create a Page method that converts a file path to a server relative URL. I do this by skipping over Server.MapPath("/").Length-1 characters. I don't want to compute that value every time I call the function, and I can't use a class variable for it. In C++, a static local variable is exactly what I would use.

  • Anonymous
    October 07, 2014
    Interesting discussion.  I used static method variables in VB 6 all the time, for things like recursive procedure calls.  Probably the reason that they're supported in VB.Net is because they were supported in VB 6.  I'm in the "pro" camp.

  • Anonymous
    November 14, 2014
    I must join the moan about recursive functions, where static variables allow a very straightforward code. Now you have to declare them in classes (why? There are cases where they are specific in certain procedures) and reset them using another method to simulate that they are initialized when created :-( Don't know if there's another method to reproduce the original behavior, but this one is pretty ugly.

  • Anonymous
    January 14, 2015
    Funny. This topic is 11 years old, but people keep getting back to it. Because not being able to use method-level static variables is a pain in the a**. I would love to get rid of C#. This is just one of the problems I see with C#. A language should be a tool to solve problems, not a showcase how clean it is (on paper). That will only lead to dirty results. I prefer a dirty tool in order to have a clean result.

  • Anonymous
    March 27, 2015
    So with multi threading, we have the problem where each function needs a Mutex or two (one for the start of the function and one for the end, but the middle is thread safe once it gets started), and there should be a separate Mutex for each function as the functions do not interact with the same non-thread safe constructs.  So a class with a few dozen functions that has thread safety issues that have to be solved by separate mutexes has a major name space pollution problem.  If method static functions were allowed, the namespace pollution problem would disappear.   Yet another reason to not like C#.

  • Anonymous
    May 21, 2015
    I would bet the best rock from my garden that barely a handful of people care about method-level statics. Of those, most accept that declaring a static field is pretty much the same thing, excepting that the field appears in intellisense throughout the class. Such "namespace pollution", as some have called it, smells a whole lot better than concealing static state within non-statics. This is barely the kind of complaint worthy of issuing blanket statements for or against the use of a language. The examples provided in favor of method-level statics tend to be pretty convoluted and/or obscure. Of all the things the language and tool developers could do to add value to this language, this has to be pretty low on the totem pole, and for good reasons.

  • Anonymous
    August 27, 2015
    I am certainly in the "pro" camp ... my best current workaround is the "initialize-it-once property" approach.  But that DOES add overhead in the form of [function call, extra state checking code].  I don't know if it could be done without adding some of that overhead, though. The most reasonable argument (IMO) is the "thread safety" issue.  I hadn't really thought of that.  So, to put it up for discussion - what if "static variables" were allowed in (and only in) static functions?  That would certainly resolve the thread safety issue, and might force people to really think about the need for a static variable... What does everyone else think

  • Anonymous
    October 28, 2015
    The comment has been removed