C # Initialize a local variable once

I suppose my question would be completely stupid, but I should know the answer.

Is it possible to initialize a variable only once in this situation?

    static void Main()
    {
        while (true)
        {
            MethodA();
            MethodB();
        }
    }

    private static void MethodA()
    {
        string dots = string.Empty;    // This should be done only once

        if (dots != "...")
            dots += ".";
        else
            dots = string.Empty;

        Console.WriteLine(dots + "\t" + "Method A");
        System.Threading.Thread.Sleep(500);
    }

    private static void MethodB()
    {
        string dots = string.Empty;    // This should be done only once

        if (dots != ".....")
            dots += ". ";
        else
            dots = string.Empty;

        Console.WriteLine(dots + "\t" + "Method B");
        System.Threading.Thread.Sleep(500);
    }

Of course, I can initialize the string points outside the method, but I do not want to mess up the code, and this cannot be done in any other loop (for example, for). Any ideas how to solve this problem, or am I so stupid to think normally?

Thanks in advance.

EDIT: I modified the sample code to be more practical. The required conclusion should be:

.    Method A
.    Method B
..   Method A
..   Method B
...  Method A
...  Method B
     Method A
.... Method B
.    Method A
.....Method B

Etc. and etc.

+5
source share
5 answers

, , ( Method), , , , , .

string Method(string dot = string.Empty)
{
   if(dot == "...") return string.Empty;
   else return dot + ".";
}

var result = Method(Method(Method(Method(Method(Method()))))) // etc...

EDIT: . : X, # X. ++ VB.NET.

" ?"

, NO!

+3

dots , , ..

string dots = string.Empty; 
private void Method()
{
    if (dots != "...")
        dots += ".";
    else
        dots = string.Empty;
}
+3

(++) . , # . #: # ?.

, , , . - currying, , . , , , , .

, , . # (?) - .

+2
+1

Are you thinking of a static local variable like in C ++ ? They are not supported in C #, as discussed here .

0
source

All Articles