I have three .cshtml created using WebMatrix:
MyClass.cshtml located at App_Code:
@functions
{
public static string x;
public static void setX()
{
x = "some data";
}
}
WithSet.cshtml located at the root:
@{
MyClass.setX();
}
@MyClass.x
WithoutSet.cshtml located at the root:
@MyClass.x
When I visit WithSet.cshtml, MyClass.x will be set to “some data” and after that, when I visit WithoutSet.cshtml, still the MyClass.x contains “some data”. I was expecting that class to be fresh, not initialized and so MyClass.x. I think I don’t fully understand what is going on, what is the life span of the class? Is the class here static?
Because static objects are shared across the app domain in .net – all users will get the same instance of the class with that static variable having been set.
http://www.foliotek.com/devblog/avoid-static-variables-in-asp-net/
There is a good explanation of what the implications of using static fields in .net are.