I'm trying to override method ToString() to return value of a field in my class and clear that field (return value only once). I've noticed that the code seems to work when I'm running it without any interruption to the end (at least pass the overriden method), but when debugging step-by-step it returns no value, and it looks like there is no value stored at the init of the object.
I've managed to fix this issue by changing the name of the method from ToString() to other not overrided name, also commenting the line text = ""; makes it work, but I don't know why.
The same was happening when I tried to assign a StringBuilder value to temp var, clear StringBuilder and return temp value. I'm curious what causes that strange behavior.
class Program
{
public class MyClass
{
private string text = "some value";
public override string ToString()
{
string temp = text;
text = "";
return temp;
}
}
public class MyClass2
{
private string text = "some value";
public override string ToString()
{
return text;
}
}
static void Main(string[] args)
{
MyClass obj = new MyClass();
MyClass2 obj2 = new MyClass2();
Console.WriteLine("1 MyClass: " + obj.ToString());
Console.WriteLine("1 MyClass2: " + obj2.ToString());
Console.WriteLine("2 MyClass: " + obj.ToString());
Console.WriteLine("2 MyClass2: " + obj2.ToString());
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
When I run the code to the ReadKey(); without interrupts the output is:
1 MyClass: some value
1 MyClass2: some value
2 MyClass:
2 MyClass2: some value
Press any key to exit
When stepping through the code with F10 the output is:
1 MyClass:
1 MyClass2: some value
2 MyClass:
2 MyClass2: some value
Press any key to exit
ToStringshould not have side-effects.ToString()anyway just create a method with better name, e.g.GetStringAndReset().debuggerdisplayattributelearn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/…