Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ASP.Net Webforms - string - static vs static readonly

Tags:

c#

asp.net

I have hit a bit of confusion in regards to using these varibles within an ASP.Net application.

public static string Complete = "Complete";

As far i'm aware, this value will be global for all users, but the value is not guaranteed to exist due to the application pool recycling and the value is not assigned on recycle?

public static readonly string Complete = "Complete";

Does the readonly flag mean that the value is always available due to getting initialized with the static constructor of the class, meaning that the value will always be available?

As far as I'm aware, the following would happen in the readonly scenario:

  1. Access Variable
    • Is class constructed? No? Assign variable
  2. Application Restarts
  3. Go to 1

Is there any difference between the readonly and non-readonly version? I suppose we could also write it as follows to guarantee the variable:

public static string Complete { get { return "Complete"; } }

like image 347
Hux Avatar asked Nov 02 '11 09:11

Hux


1 Answers

readonly will simply stop the value held by the variable being changed once initialized. It doesn't affect the life time of the static - it is still the same as before.

Note that if the static is a reference, the readonly attribute doesn't stop the underlying object from being mutated, it only stops the value of the static variable from being changed - in the case of a class reference, that value is the reference itself.

MSDN C# docs on readonly:

http://msdn.microsoft.com/en-us/library/acdd6hb7(v=VS.100).aspx

A readonly static will have a similar affect to a const (assuming the thing you are making static is elligible for const) when you talk about having a global unchanging value. When you first attempt to access the static, it will be initialized on the spot and never be allowed to change.

So:

public static readonly string Something = "what";

Will in effect behave like:

public const string Something = "what";

Although the latter is compile time constant, and the former isn't - so it's behaviour has some key differences. I was more talking about the idea of a value available globally that doesn't change.

In terms of ASP.NET and recycling of statics, the difference between the readonly static and const is that the static simply incurs the charge of initializing if it hasn't been initialized yet. However for the usage being described, const is a better fit.

like image 178
Adam Houldsworth Avatar answered Sep 30 '22 00:09

Adam Houldsworth