Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 487
markzzz Avatar asked Dec 07 '11 09:12

markzzz


People also ask

What is the difference between toString () and convert toString ()?

Convert. ToString() handles null , while ToString() doesn't. Save this answer.

What is the difference between toString () and valueOf () in Java?

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.

What is to toString () method for?

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).

What is the purpose of toString () and equals () methods in Java class?

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.


1 Answers

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() : ""
like image 164
Mark Byers Avatar answered Sep 25 '22 20:09

Mark Byers