Static Properties and Application

ANB 181 Reputation points
2023-02-14T23:02:15.6466667+00:00

I would like to understand better how static data works and how they are shared around the application.

Let's say I have a class Car and all its properties start with value = 0;
public static class Car {
int qtyPassengers { get; set; }
int Year { get; set; }
}

So User "A" visits my website and in a specific method, he/she changes the Car Year value to 2015.

What I have heard is that Static classes/properties/data lasts for the lifetime of the application.
Does it mean that if User "B" in a different country access the same website, in a different computer, will have the value 2015 for the Year ?

Thx

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-02-14T23:57:38.72+00:00

    Static fields and properties are global application variables. There is one variable for the entire application. If user A sets the year to 2015 every web application user sees 2015. That is until someone else updates the variable. Then everyone see the new value. A static field or property is not thread safe and allows data leakage. Although there are times when a static type (Singleton Pattern) are just what the application needs.

    A static class behaves differently than a static field or property. A static class is a class with at least on static method. While the scope of a static field or property is the application, the scope of variables within a static method are the method body.

    See the C# programming guide for a complete explanation and code samples.

    Static Classes and Static Class Members (C# Programming Guide)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.