Tales from the trenches: ASP.Net static variable bug


This post is part of a series of actual problems or bad practices I encountered working on existing C# code bases.

The names of all identifiers, the exact functionalities of the programs and the code samples have all been altered for confidentiality reasons.

While working on an ASP.Net control bug, I noticed this more important problem which hadn’t been reported.

The reported bug was about a control that would sometimes not repopulate itself. It was a pretty simple case.

if (ConditionA && lastValue != currentValue)
{
    lastValue == currentValue;
    // more code
}

What happened is that when ConditionA failed, lastValue wasn’t updated. The fix was simply to move the lastValue assignment statement outside of the conditional.

The bigger problem I noticed was when I decided to look at how lastValue was implemented.

It turned out it was implemented as a static member variable. This being an ASP.Net page, a static variable is shared between all instances of the class in the AppDomain.

What this effectively means is that every user of the site shares this same variable.

Suppose user A fills lastValue with “test”, then user B fills currentValue with “test”, the server-side code detects that user B has already used this value as his value (since it’s currently in lastvalue), even if he hasn’t entered anything before. This could lead to some inconsistent behaviour.

The lesson here is two-fold:

1- Do not to cache information with a static variable in an ASP.Net site unless that information is not subject to change from user to user.

2- When working on existing code, make sure you understand correctly how it is implemented. In this case I could have glossed over the implementation of lastValue, which wasn’t declared near the method I was working on and missed this important bug.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s