Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Static readonly' vs. 'const'

Tags:

c#

constants

I've read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my observation is correct:

Should these kind of constant values always be static readonly for everything that is public? And only use const for internal/protected/private values?

What do you recommend? Should I maybe even not use static readonly fields, but rather use properties maybe?

like image 792
Svish Avatar asked Apr 16 '09 11:04

Svish


People also ask

What is the difference between static readonly and constant?

Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor. Constant variables cannot be modified after declaration. Static members can be accessed using ClassName.

Should I use const or static?

const is a constant value, and cannot be changed. It is compiled into the assembly. static means that it is a value not related to an instance, and it can be changed at run-time (since it isn't readonly ). So if the values are never changed, use consts.

What is the use of static readonly in C#?

A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further.

Are static variables read-only?

Read-only variables can't access without a class instance. Static readonly: We can define static readonly variable values while declaring as well as only through a static constructor, but not with any other constructor. We can also access these variables without creating a class instance (as static variables).


2 Answers

public static readonly fields are a little unusual; public static properties (with only a get) would be more common (perhaps backed by a private static readonly field).

const values are burned directly into the call-site; this is double edged:

  • it is useless if the value is fetched at runtime, perhaps from config
  • if you change the value of a const, you need to rebuild all the clients
  • but it can be faster, as it avoids a method call...
  • ...which might sometimes have been inlined by the JIT anyway

If the value will never change, then const is fine - Zero etc make reasonable consts ;p Other than that, static properties are more common.

like image 189
Marc Gravell Avatar answered Oct 15 '22 05:10

Marc Gravell


I would use static readonly if the Consumer is in a different assembly. Having the const and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.

like image 28
Michael Stum Avatar answered Oct 15 '22 06:10

Michael Stum