Is there a specific reason String.Empty is not Const?

Possible duplicate:
Why is not String.Empty constant?

I wanted to use string.Empty in the attributes of several of my properties, but since then I have seen that this is not a Constant, but a static member.

Is there any reason Microsoft would do this?

+4
source share
2 answers

I would say that it is always a bad idea to use const in reference assemblies.

The reason is because the C # compiler treats constants as values, not as references, as I said in this.

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

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

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

+5
source

I think the reason is this: string is a reference type, not a value type. and itโ€™s faster to compare two links (when you use a static member) than two line instances (when using const)

0
source

Source: https://habr.com/ru/post/1345889/


All Articles