简体   繁体   中英

Why does C# not allow variables to be declared static in methods?

I'm reading some AppHub samples by Microsoft and this is the beginning of one of the functions:

if (string.IsNullOrEmpty(textureFilename))
{
    string message = "textureFilename wasn't set properly, so the " +
        "particle system doesn't know what texture to load. Make " +
        "sure your particle system's InitializeConstants function " +
        "properly sets textureFilename.";
    throw new InvalidOperationException(message);
}

ReSharper says to make this value a constant rather than redeclaring it every time. However, this string value is only used in this function, so making it a member variable should not be necessary. Ideally, the variable's scope should be limited to this function. Right?

Also, I agree with whoever is about to say "place the string in a resource file." In this case that would most likely be the optimal solution. Not only does it solve localization issues but it also saves the variable from being re-initialized every function call and no longer clutters up the source file. However, this is just an example.

I know many are probably going to say something along the lines of "premature optimization is the root of all evil" but please note this is just an example. What if this quasi-constant variable was complex and re-initializing it every call would cause a noticeable slowdown?

Visual Basic .NET allows the programmer to declare variables in a function as static. For example, in this code TestFunction will only be called the first time I click the button:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Static example As Integer = TestFunction()

    MessageBox.Show(example)
End Sub

Private Function TestFunction() As Integer
    Console.WriteLine("Method Accessed")

    Return 5
End Function

As far as I know C# does not allow this. Is there any particular reason why? It seems like it would be perfect in this situation. It limits the variables scope to the function and only initializes it the first time around. Even if object creation is costly it will only be performed once. So why is this not available? Or is it?

Thanks for reading!

ReSharper says to make this value a constant rather than redeclaring it every time. However, this string value is only used in this function, so making it a member variable should not be necessary. Ideally, the variable's scope should be limited to this function. Right?

Yes, but resharper will make the local variable const, not create a member field

if (string.IsNullOrEmpty(textureFilename))
{
    const string message = "textureFilename wasn't set properly, so the " +
        "particle system doesn't know what texture to load. Make " +
        "sure your particle system's InitializeConstants function " +
        "properly sets textureFilename.";
    throw new InvalidOperationException(message);
}

Is there any reason why you don't want to make it a local const , as ReSharper suggests?

if (string.IsNullOrEmpty(textureFilename))
{
    const string message = "...";
    throw new InvalidOperationException(message);
}

There is a blog post in the C# FAQ about this exact question .

Effectively, there are two reasons. First, you can accomplish the same thing via a const or via a member level static variable in nearly all situations. Secondly, local static variables in other languages (like C and C++) frequently cause problems in multithreaded scenarios.

In addition, I am happy this was left out. State, as data, the way it is in C#, only exists tied to a type or to an instance. This would be making a third way to store state, and add confusion.

As to why VB.Net included this - this was included for backwards compatibility with VB. That being said, the compiler actually turns this into a static member of the type, so its really the same level of support as C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM