Sunday, April 1, 2012

What is the difference between const and static readonly?

The difference is that the value of a readonly field is set at run time, so it can have a different value for different executions of the program. However, the value of a const field is set to a compile time constant.

 

 

Readonly instance fields

  • Must have set value, by the time constructor exits
  • Are evaluated when instance is created

Static readonly fields

  • Are evaluated when code execution hits class reference (when new instance is created or a static method is executed)
  • Must have an evaluated value by the time the static constructor is done
  • It's not recommended to put ThreadStaticAttribute on these (static constructors will be executed in one thread only and will set the value for its thread; all other threads will have this value uninitialized)

Constants

  • Constants are static by default
  • They must have a value at compilation-time
  • Could be declared within functions
  • Are copied into every assembly that uses them
  • Can be used in attributes

 

 

Check this video out for more understanding :

 

No comments:

Post a Comment

Live

Your Ad Here