Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use public const with strings?

Tags:

c#

constants

I have heard that it is a bad idea to do something like:

public const double Pi = 3;

because later when I realise I need to change it to 3.14, other assembillies will not be able to see the change until they are recompiled too. Therefore readonly would be a better choice.

Does the same apply to strings? For example with

public const string Name = "Buh";

it is only the reference that is constant, right? Or does the compiler do something clever here?

Is the the string literal, "Buh" inlined into other assemblies? Or is only the reference to "Buh" inlined?

like image 685
Buh Buh Avatar asked Dec 22 '25 07:12

Buh Buh


1 Answers

The thing is that the compiler, before the IL is generated, will replace all constants with the actual value of the constant, so it does not matter what type it is. If it's a string, double, int or whatever, the assemblies that use the const will continue to use the old value untill they are recompiled, since the compiled IL has no knowledge of any constant ever existing. It just know about the value itself, just like if you had hardcoded it directly.

readonly on the other hand is evaluated like other non-readonly fields, and therefore changes will be seen by other assemblies regardless of the type of the readonly field.

like image 114
Øyvind Bråthen Avatar answered Dec 23 '25 19:12

Øyvind Bråthen