string.Empty vs null.Which one do you use?

前端 未结 5 1918
不思量自难忘°
不思量自难忘° 2020-11-30 23:31

Recently a colleague at work told me not to use string.Empty when setting a string variable but use null as it pollutes the stack?

He says

5条回答
  •  渐次进展
    2020-12-01 00:11

    It doesn't 'pollute the stack', there's no technical reason but there is a big difference between setting a variable to a reference to an object (even if it's an empty string) and null. They are not the same thing and should be used in different ways.

    null should be used to indicate the absence of data, string.Empty (or "") to indicate the presence of data, in fact some empty text. Is there a specific case where you're not sure what is the most appropriate?

    Edit, added examples:

    • You might use string.Empty as the default postfix for a person's name (most people don't have PhD for example)

    • You might use null for a configuration option that wasn't specified in the config file. In this case, string.Empty would be used if the config option was present, but the desired configured value was an empty string.

提交回复
热议问题