Is there a specific reason that String.Empty is not a Const? [duplicate]
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?
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.
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)
精彩评论