What are the differences between .ToString () and + ""

If I have a DateTime and I do:

date.Year.ToString()

I get Year as String. But also if I do

date.Year + ""

the differences are only that the second does not receive an exception if there is no Date? (which i prefeer)

+5
source share
3 answers
date.Year.ToString()

Will not work if the date is zero.

date.Year + ""

It works even if the year is zero, because the binary + operator replaces zero with an empty string.

This is what MSDN says that the binary + operator concatenates two strings:

binary + , . NULL, . , ToString, . ToString null, .

http://msdn.microsoft.com/en-us/library/aa691375%28VS.71%29.aspx

+4

date.Year + "", string.Concat(object, object):

String.Concat(date.Year, "")

Concat ToString ( ) .

NullReferenceException, date null. , date DateTime. DateTime .


date DateTime? , , :

date.HasValue ? date.Value.Year.ToString() : ""
+10

It date.Yearmakes no difference if it is not null.

In the second example, the method is ToString()implicitly called date.Year.

+3
source

All Articles