简体   繁体   中英

What's the differences between .ToString() and + “”

If I have a DateTime, and I do :

date.Year.ToString()

I get the Year as String. But Also if I do

date.Year + ""

the differences is only that the second one doesnt get an exception if there isn't the Date? (which i prefeer)

When you write date.Year + "" it will be compiled as a call to string.Concat(object, object) :

String.Concat(date.Year, "")

Internally, the Concat method will call ToString on each (non-null) object.

Both approaches will throw a NullReferenceException if date is null . But you said date is of type DateTime . DateTime is a struct and so cannot be null.


If date is of type DateTime? and want to return an empty string if date is null then you can use this:

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

Won't work if date is null.

date.Year + ""

Works even if year is null as binary + operator substitutes null with a empty string.

This is what MSDN says about binary + operator concatenating two strings:

The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

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

There is no difference if date.Year is not null.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM