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

I was a little confused about using these varibles in an ASP.Net application.

public static string Complete = "Complete";

As far as I know, this value will be global for all users, but the existence is not guaranteed due to reuse of the application pool and the value is not assigned for reprocessing?

public static readonly string Complete = "Complete";

Does readonly flag mean that this value is always available due to initialization with the static constructor of the class, which means that the value will always be available?

As far as I know, the following will happen in the readonly script:

  • Variable access
    • Is the class created? No? Assign Variable
  • Application restart
  • Go to 1

Is there a difference between the readonly and non-readonly versions? I suggest that we could also write it as follows to guarantee a variable:

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

+4
source share
3 answers

readonly simply stop the value held by the variable, which will be changed after initialization. This does not affect the static lifetime - it is still the same as before.

Note that if static is a reference, the readonly attribute does not stop changing the underlying object, it only stops changing the value of the static variable โ€” in the case of a class reference, that the Value is the link itself.

C # MSDN docs on readonly:

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

A readonly static will have a similar effect on const (assuming you are making static isible for const ) when you talk about having a global immutable value. When you first try to access the statics, it will be initialized in place and will never be changed.

So:

 public static readonly string Something = "what"; 

Will behave like:

 public const string Something = "what"; 

Although the latter is a compile-time constant, the former is not - therefore, the behavior has some key differences. I talked more about the idea of โ€‹โ€‹value, accessible throughout the world, which does not change.

In terms of ASP.NET and static utilization, the difference between static readtly and const is that static simply takes an initialization charge if it has not already been initialized. However, const better suited to describe usage.

+4
source

public static string Complete = "Complete";

. But it can also be changed. Use const if you want it to be a constant.

Additional information abot const vs readyonly vs static readonly Here

0
source

The readonly keyword tells the compiler that this class variable can only be initialized with its declaration or in its c'tor (since this is a static field, these two options are equivalent anyway).

In addition, there is no other difference.

HTH - Thomas

0
source

Source: https://habr.com/ru/post/1379268/


All Articles