AngieM AngieM - 1 year ago 68
C# Question

C# Class Property Getter Invoked Automatically

I have 2 class properties defined like so:

private static string _validationError;
public static string ValidationError
get {
var temp = _validationError;
_validationError = "abc";
return temp;

set { _validationError = value; }

public static string CurrentError { get; set; }

A method:

public static bool IsErrorStringEmpty()

return false;

Test Method:

public void ValidationErrorTest()
CurrentError = "My Error";

var empty = IsErrorStringEmpty();

When I debug this test, this is the behavior I'm seeing:

  1. Before the 2nd line of the test method is hit, ValidationError = null (Expected).

    enter image description here

  2. When it enters IsErrorStringEmpty(), before the 1st line is hit, ValidationError = null (Expected).

    enter image description here

  3. Then, right when it's hitting the 1st line, ValidationError = "abc". I don't know how this getter is being invoked at all even though I have no explicit code up to this point to access the ValidationError property.

    enter image description here

I have breakpoint in the getter, but it didn't get hit, and the Call Stack is shown as below.

enter image description here
enter image description here

I'm sure it's somewhere but I can't seem to find it. Any pointers are greatly appreciated!

Answer Source

You're invoking the getter in the debugger. When code is executed in the evaluation of a property for display in a watch window it is really being executed, with real side effects.

Try watching _validationError instead.

Side effects in a getter can throw you for a loop. Best to avoid them.