4

Possible Duplicate:
Why isn't String.Empty a constant?

I wanted to use string.Empty in the Attributes of a few of my properties, but have since seen that it is not actually a Const but a static member.

Is there any reason Microsoft would do this?

Community
  • 1
  • 1
Dan
  • 12,808
  • 7
  • 45
  • 54

2 Answers2

5

I would say it's always a pretty bad idea using const in referenced assemblies.

The reason being the fact that the C# compiler treats constants as values and not as references, as I've said in this answer.

With this I mean that the C# compiler will replace all instances of the constant in you code and replace the "variable" with the value.

This means that even if you update the assembly GlobalConstants.dll and copy it to one of the applications you have, you will need to recompile that application. Not doing so, will cause the application to use the old constant values.

To overcome this problem, you can simply use public static readonly instead of public const as the readonly modifier differs from the const in that it is treated by the C# compiler as a reference in code rather than a value.

Community
  • 1
  • 1
Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
  • 1
    Always a bad idea? Can you envisage a situation where "the empty string" or `Math.PI` would change, for example? – Jon Skeet Dec 13 '11 at 07:10
  • 1
    How unfair of you to dig this up, Mr Skeet. Reading the question and my answer again, makes me wonder what I was thinking. I think my answer should have remained on the other question I had answered where I think it is valid. For this question, not so much. I'd give myself a down vote if I could. – Mikael Östberg Dec 13 '11 at 12:32
0

I think that the reason is: string is reference type, not value type. and it is faster to compare two references (when you use static member) than two instances of strings (when you use const)

Marek Kwiendacz
  • 9,524
  • 14
  • 48
  • 72