Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - Why is the default value of the string type null instead of an empty string?

It's quite annoying to test all my strings for null before I can safely apply methods like ToUpper(), StartWith() etc...

If the default value of string were the empty string, I would not have to test, and I would feel it to be more consistent with the other value types like int or double for example. Additionally Nullable<String> would make sense.

So why did the designers of C# choose to use null as the default value of strings?

Note: This relates to this question, but is more focused on the why instead of what to do with it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why is the default value of the string type null instead of an empty string?

Because string is a reference type and the default value for all reference types is null.

It's quite annoying to test all my strings for null before I can safely apply methods like ToUpper(), StartWith() etc...

That is consistent with the behaviour of reference types. Before invoking their instance members, one should put a check in place for a null reference.

If the default value of string were the empty string, I would not have to test, and I would feel it to be more consistent with the other value types like int or double for example.

Assigning the default value to a specific reference type other than null would make it inconsistent.

Additionally Nullable<String> would make sense.

Nullable<T> works with the value types. Of note is the fact that Nullable was not introduced on the original .NET platform so there would have been a lot of broken code had they changed that rule.(Courtesy @jcolebrand)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...