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)
Convert. ToString() handles null , while ToString() doesn't. Save this answer.
valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String. valueOf by default when something like String s = "" + (...); is used.
The toString() method Typically, it is used to construct a string containing the information on an object that can be printed, and we can redefine it for a certain class. If we do not redefine it, the toString() method of the class Object is used (which prints a system code for the object).
The toString method is used to return the String representation of an object (converting an object to a String). Like equals , all Java objects have a toString method. However, also like equals not all classes provide particularly useful implementations.
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() : ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With