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.
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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With