Nullable ToString()

前端 未结 6 1919
清歌不尽
清歌不尽 2020-12-13 22:39

I see everywhere constructions like:

int? myVar = null;
string test = myVar.HasValue ? myVar.Value.ToString() : string.Empty;

Why not use

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 23:28

    You are quite correct. Also in this question, the former solution is suggested while nobody actually notices ToString() already gives the correct answer.

    Maybe the argument for the more verbose solution is readability: When you call ToString() on something that is supposed to be null, you usually expect a NullReferenceException, although here it isn't thrown.

提交回复
热议问题