Buh Buh
Buh Buh

Reputation: 7545

Is it safe to use public const with strings?

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?

Upvotes: 3

Views: 258

Answers (3)

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

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.

Upvotes: 2

Kieren Johnstone
Kieren Johnstone

Reputation: 41993

http://weblogs.asp.net/psteele/archive/2004/01/27/63416.aspx

const is compile-time, so you're right: use readonly if it might change in the future!

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

strings are immutable, so it is the same as for double.

Upvotes: 1

Related Questions