Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Initialize local variable once

I assume my question will be totally stupid but I have to know the answer.

Is it possible to initialize a variable just 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 string dots out of method but I don't want to do mess in the code, and this can't be done in any other loop too (like for). Any ideas how solve this or am I so stupid to think normally?

Thanks in advance.

EDIT: I've changed the sample code to be more practical. Desired output should be:

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

Etc. etc.

like image 273
Michał Sokołowski Avatar asked Jul 20 '12 16:07

Michał Sokołowski


2 Answers

You said you don't want to keep the dots out side of Method (in the Method's class), then you must return the value from Method so that you can at least pass it in later on, thus persisting its state.

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

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

EDIT: Your edited question does not make your initial problem more practical. It still suffers from the same problem: You want X but C# does not have X. Use C++ or VB.NET instead.

The answer to your question

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

is Sorry, NO!

like image 145
Jake Avatar answered Oct 03 '22 11:10

Jake


You could keep dots in your class, and initialize it when the class is created, i.e.

string dots = string.Empty; 
private void Method()
{
    if (dots != "...")
        dots += ".";
    else
        dots = string.Empty;
}
like image 38
Ryan Avatar answered Oct 03 '22 11:10

Ryan