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!
Yes, but resharper will make the local variable const, not create a member field