Reputation: 67
Good evening to all. Something really strange has happened to me. After many tests, I discovered that, in debug mode (Visual Studio 2017), after the appearance of the DataTip via mouse hover on the property, it was independently instantiated and set as empty. Is it a bug in Visual Studio or is there a reason why this thing happens?
private List<int> myVar;
public List<int> MyProperty
{
get
{
if (myVar == null)
{
myVar = new List<int>();
return myVar;
}
else
return myVar;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
List<int> list = MyProperty;
}
As you can see, if you place the mouse on myVar you get null correctly, but if you place it on MyProperty it is instantiated automatically and immediately myVar is instantiated too.
This behavior created a lot of problems to me during debugging, and it took me a long time to figure out what was going on. Is it the normal behavior or is it a bug? Please note that I didn't provide the set accessor.
Upvotes: 2
Views: 192
Reputation: 3235
It is the normal behavior.
MyProperty
's getter invokes each time you try to get its value. Hovering when debugging counts too. If you place the cursor over myVar
avoiding MyProperty
it will be myVar|null
, but once you place it over MyProperty
, the whole getter invokes and you see MyProperty|Count = 0
. Since then myVar
is myVar|Count = 0
too (because it's changed in the getter). If you put a counter to know how many times getter invokes, you will see how it changes.
By the way,
private List<int> myVar;
public List<int> MyProperty => myVar ?? (myVar = new List<int>());
does the same, but looks neater;)
Upvotes: 6