Nullable ToString()

前端 未结 6 1933
清歌不尽
清歌不尽 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:35

    No, you're correct, the shorter version is the same as what other folks have done in that regard. The other construct I tend to use a lot instead of the ternary with nullables is the null coalescing operator,. which also protects you from nulls. For ToString() it's not necessary (as you pointed out) but for default int values (for example) it works nicely, e.g.:

    int page = currentPage ?? 1;
    

    that lets you do all the integer operations on page w/o first explicitly null checking and calling for the value in currentPage (where currentPage is an int? perhaps passed as a param)

提交回复
热议问题