My tech friend recently shared a tweet highlighting the risks of incorrectly utilizing static fields in Microsoft .NET. Coincidentally, I had recently discussed this topic with another software engineer. It reminded me of an issue I had resolved for an insurance company involving data corruption. I’ll share that story at the end of this article. In this piece, I’ll delve into the various ways of using the static keyword in .NET and concentrate on coding static fields in non-static classes.
In Microsoft .NET, a static field is a variable associated with a type rather than an instance of the type. This means that the value of the static field is shared across all instances of the type, and it is not unique to each individual instance.
Static fields are declared using the “static
” keyword, and they can be accessed using the name of the type rather than an instance of the type. For example, consider the following class from my OOS Spargine:
public static class App { private static readonly Lazy<AppInfo> _appInfo = new(() => InitAppInfo()); // Code removed for brevity }
In this example, this static field _appInfo
is initialized when the class is created and, in this case, gathering the data is delayed until the field is first hit.
Static fields are commonly used to store data that is shared across all instances of a type, such as a counter that keeps track of how many instances of the type have been created, or a configuration setting that is common to all instances of the type.
It is important to note that static fields can introduce issues with concurrency and thread safety, as multiple threads may attempt to access and modify the same static field simultaneously. To avoid these issues, it is recommended to use thread-safe techniques such as locking or the Interlocked class when working with static fields in a multi-threaded environment.
Be Very Careful Using Static Fields
Static fields pose a significant risk when used improperly, particularly when developers are unfamiliar with how they work in memory. Initializing a static field will cause it to remain in memory until the application ends, regardless of whether it’s still needed. Therefore, developers need to be cautious when selecting the types of data stored in these fields, as well as the amount of memory required.
Let’s take an example of an ASP.NET website where a user, Susan, logs in. During the login process, an object called CurrentUser
is created, which connects to the database and loads Susan’s personal information based on her email address. The information is then stored in a private static field. When the GetUser()
method is called, it retrieves Susan’s information to log her in. However, if John logs in later, a new CurrentUser
object is created, loading John’s information and overwriting Susan’s. This can result in displaying incorrect information, such as John’s data being shown when Susan’s details are requested.
This illustrates why it is crucial to avoid using static fields unless necessary and to carefully weigh the potential risks and trade-offs before introducing them into a codebase.
Real World Story
During the mid-2000s, I worked for a reputable consulting company in San Diego, California. We often collaborated with companies like Microsoft. One day, an insurance company in San Diego approached us with an urgent issue. Their website was displaying personal information from other customers during the new user signup process. Given the sensitive nature of personal information, it was crucial to resolve the issue as soon as possible to avoid any legal consequences or fines.
Upon arriving at the company, the manager explained the issue that they had been struggling with for over a month. I sat down with the developer at her computer to try to identify the problem. After about two hours, I realized that the class field storing users’ personal information was static. I explained how static fields work and convinced her to remove “static” from the field definition. With this simple fix, the issue was resolved.
The development manager was pleased with my quick discovery of the issue and asked me to review the entire codebase. However, I was disappointed to learn that I wouldn’t have access to the source code. Instead, I had to review a printed copy of the code. This highlights the importance of keeping classes well-documented and consistently formatted, as you never know how they may be viewed.
After two weeks, I presented management with my code review and recommendations for improvement. However, the developer pushed back and refused to listen to my advice. Due to her unwillingness to cooperate, I recommended that management find a new lead developer, which they did a month later.
Summary
When I review code and see a static field, it raises a red flag and I make sure that it’s being used properly. After reading this article, I hope you will treat static fields the same way I do. If you do, you will write better, stable code.
If you have any questions about this article, please share them in the comments below, I’d love to hear from you.