C #: should "" assign a string to make it empty?

Should "" be assigned to a string to make it empty?

Or should it be left as null?

+3
source share
4 answers

You can use any of them, but the canonical way is to assign it a value

string.Empty
+6
source

IMHO, the best approach is to assign it as String.Empty if you want it to be an empty string (and not null).

+5
source

. null, . , , , , , , . , - .

public string Foo( string bar )
{
    bar = bar ?? string.Empty;

    return bar.ToLower();
}

, , , .

public string Foo( string bar )
{
    return bar == null ? null : bar.ToLower();
}
+4

Depends on what you are going to do with the string. If you set it to ", this is a valid object and will not throw a null reference exception when you pass it to any function that expects a string. But you also lose the ability to do (fast)" if (str == null) " , and the runtime calls a function call to compare strings.

+1
source

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


All Articles